<?php

namespace Api\Controller;

use Think\Controller;
use Think\Model;
use JPush\Model as M;
use JPush\JPushClient;
use JPush\JPushLog;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
use JPush\Exception\APIConnectionException;
use JPush\Exception\APIRequestException;

class IndexController extends Controller {
	private $juli;
 	protected $push;
	protected function _initialize() {
	    $this->juli=3100;
	    ini_set('date.timezone','Asia/Shanghai'); 
	    date_default_timezone_set('PRC');
		Vendor('Psr.Log.LoggerInterface');
		Vendor('Httpful.Httpful');
		Vendor('Httpful.Request');
		Vendor('Httpful.Http');
		Vendor('Httpful.Bootstrap');
		Vendor('Monolog.Formatter.FormatterInterface');
		Vendor('Monolog.Formatter.NormalizerFormatter');
		Vendor('Monolog.Formatter.LineFormatter');
		Vendor('Monolog.Registry');
		Vendor('Monolog.ErrorHandler');
		Vendor('Monolog.Logger');
		Vendor('Monolog.Handler.HandlerInterface');
		Vendor('Monolog.Handler.AbstractHandler');
		Vendor('Monolog.Handler.AbstractProcessingHandler');
		Vendor('Monolog.Handler.StreamHandler');
		// Vendor('JPush.Model.Audience');
		// Vendor('JPush.Model.PushPayload');
		// Vendor('JPush.Model.Options');
		// Vendor('JPush.Model.Platform');
		// Vendor('JPush.Model.Notification');
		// Vendor('JPush.JPushLog');
		// Vendor('JPush.JPushClient');
		$JPsetting=C('jpush');
		$app_key =$JPsetting['app_key'];
		$master_secret = $JPsetting['master_secret'];                //改成自己的key
		//JPushLog::setLogHandlers(array(new StreamHandler('jpush.log',100)));
		//$this -> push = new JPushClient($app_key, $master_secret);
	} 
	//商家判断手机是否同时登录了多台设备
	public function multiLogin(){
	    $type=I('type');
	    $imei=I('imei');
	    $userid=I('userid');
	    if($type==1){//店主
	        $map['isBiz']=1;
	        $map['userId']=$userid;
	        $map['userStatus']=1;
	        $map['userFlag']=1;
	        $oldImei=M('users')->where($map)->getField('bizImei');
	        if($imei!=$oldImei){
	           //在不同设备登录了
	            $this->ajaxReturn(array('status'=>0));
	        }else{
	            $this->ajaxReturn(array('status'=>1));
	        }
	    }elseif($type==2){//店员
	        $oldImei=M('staff')->where(array('id'=>$userid,'staffStatus'=>1))->getField('imeis');
	        if($imei!=$oldImei){
	            //在不同设备登录了
	            $this->ajaxReturn(array('status'=>0));
	        }else{
	            $this->ajaxReturn(array('status'=>1));
	        }
	    }
	}
	
	
	//判断个人同一帐号只能一台手机登录
	public function multiUserLogin(){
	    $imei=I('imei');
	    $userid=I('userid');
	    $map ['userFlag'] = 1;
	    $map ['userStatus'] = 1;
	    $map ['userId'] = $userid;
	        $oldImei=M('users')->where($map)->getField('peImei');
	        if($imei!=$oldImei){
	            //在不同设备登录了
	            $this->ajaxReturn(array('status'=>0));
	        }else{
	            $this->ajaxReturn(array('status'=>1));
	        }
	}
	
		
	//第三方QQ登录
	public function QQLogin(){
	    $openid=I('openid');
		if(empty($openid)){
			return;
		}
	    $nickname=I('nickname');
	    $touxian=I('touxian');
	    $sex=I('sex');
	    $imei=I('imei');
	    $map['qqLogin']=$openid;
	    $map['userStatus']=1;
	    $map['userFlag']=1;
	    $info=M('users')->where($map)->find();
	    if($info){
	        $data ['lastTime'] = date ( 'Y-m-d H:i:s' );
	        $data ['lastIP'] = get_client_ip ();
	        $data ['peImei'] =$imei;
	        $m = M ( 'users' );
	        $m->where ( " userId=" . $info ['userId'] )->data ( $data )->save ();
	        $info['status']=1;
	        $info ['ip'] = get_client_ip ();
	       echo json_encode($info);
	    }else{
	        $data ['createTime'] = date ( 'Y-m-d H:i:s', time () );
	        $data ['lastIP'] = get_client_ip ();
	        $data['userName']=$nickname;
	        $data ['userStatus'] = 1;
	        $data ['userFlag'] = 1;
	        $data ['qqLogin'] = $openid;
	        $data ['userType'] = 0;
	        $data ['peImei'] = $imei;
	        $data ['userPhoto'] = $touxian;
	        $data ['userSex'] = $sex;
	        $db = M ( 'users' );
	        if ($db->create ( $data )) {
	            $r = $db->add ();
	            if ($r) {
	                $res = $db->where ( array ('userId' => $r) )->find ();
	                $res ['status'] = 1;
	                print_r ( json_encode ( $res ) );
	            } else {
	                // 注册失败
	                print_r ( json_encode ( array ( 'status' => 0) ) );
	            }
	        } else {
	            // 注册失败
	            print_r ( json_encode ( array ('status' => 0 ) ) );
	        }
	    }
	}

	
	//第三方微信登录
	public function WXLogin(){
	    $openid=I('openid');
		if(empty($openid)){
			return;
		}
	    $nickname=I('nickname');
	    $touxian=I('touxian');
	    $sex=I('sex');
	    $imei=I('imei');
	    $map['weixinLogin']=$openid;
	    $map['userStatus']=1;
	    $map['userFlag']=1;
	    $info=M('users')->where($map)->find();
	    if($info){
	        $data ['lastTime'] = date ( 'Y-m-d H:i:s' );
	        $data ['lastIP'] = get_client_ip ();
	        $data ['peImei'] =$imei;
	        $m = M ( 'users' );
	        $m->where ( " userId=" . $info ['userId'] )->data ( $data )->save ();
	        $info['status']=1;
	        $info ['ip'] = get_client_ip ();
	        echo json_encode($info);
	    }else{
	        $data ['createTime'] = date ( 'Y-m-d H:i:s', time () );
	        $data ['lastIP'] = get_client_ip ();
	        $data['userName']=$nickname;
	        $data ['userStatus'] = 1;
	        $data ['userFlag'] = 1;
	        $data ['weixinLogin'] = $openid;
	        $data ['userType'] = 0;
	        $data ['peImei'] = $imei;
	        $data ['userPhoto'] = $touxian;
	        $data ['userSex'] = $sex;
	        $db = M ( 'users' );
	        if ($db->create ( $data )) {
	            $r = $db->add ();
	            if ($r) {
	                $res = $db->where ( array ('userId' => $r) )->find ();
	                $res ['status'] = 1;
	                print_r ( json_encode ( $res ) );
	            } else {
	                // 注册失败
	                print_r ( json_encode ( array ( 'status' => 0) ) );
	            }
	        } else {
	            // 注册失败
	            print_r ( json_encode ( array ('status' => 0 ) ) );
	        }
	    }
	}
	
	
	public function Index() {
	    $str='dea7f0e2f8c7dfd0c07555b96aff2d342587505b';
	    echo count($str);
	    return;
	    echo date('Y-m-d H:i:s',1456711618);
	    echo ok;return;
	   $str='a:22:{s:8:"discount";s:4:"0.00";s:12:"payment_type";s:1:"1";s:7:"subject";s:15:"校园100购物";s:8:"trade_no";s:28:"2016022321001004260295247999";s:11:"buyer_email";s:19:"my_girl_who@163.com";s:10:"gmt_create";s:19:"2016-02-23 09:45:02";s:11:"notify_type";s:17:"trade_status_sync";s:8:"quantity";s:1:"1";s:12:"out_trade_no";s:10:"1000004714";s:9:"seller_id";s:16:"2088121427982190";s:11:"notify_time";s:19:"2016-02-23 09:45:02";s:4:"body";s:27:"校园100购物+订单号30";s:12:"trade_status";s:14:"WAIT_BUYER_PAY";s:19:"is_total_fee_adjust";s:1:"Y";s:9:"total_fee";s:4:"0.01";s:12:"seller_email";s:17:"loosoo100@163.com";s:5:"price";s:4:"0.01";s:8:"buyer_id";s:16:"2088502638936260";s:9:"notify_id";s:34:"bfd4baefc80694c0ab3545d4f66c910i0a";s:10:"use_coupon";s:1:"N";s:9:"sign_type";s:3:"RSA";s:4:"sign";s:172:"Iboq3zyhZMZpyVS3G27BolqyKmoSEpWivwgz39NLz++YbuvcXWeizvuAUwtAucxccCT6FXp85Jl7+iqFCOqt4N9jxc9jx9+bsFXaMesSydDZ3j3bANF9bQkpleZZuCCnSGNRzBdRFRRZ5WA5Ob/eMRFFNcBZ48LqqounkFMpoFY=";}';
		p(unserialize($str));
	}
	// 首页大图广告
	public function indexAd() {
		$db = M ( 'ads' );
		$date = date ( 'Y-m-d', time () );
		$where ['adPositionId'] = '-1';
		$where ['_string'] = " '$date' between  adStartDate  and  adEndDate";
		$res = $db->where ( $where )->field ( 'adId,adfile,adurl,adTypes' )->order ( 'adSort ASC' )->limit ( 3 )->select ();
		print_r ( json_encode ( $res ) );
	}
	// 首页图片切换
	public function indexSwitchAd() {
		$db = M ( 'ads' );
		$date = date ( 'Y-m-d', time () );
		$where ['adPositionId'] = '-4';
		$where ['_string'] = " '$date' between  adStartDate  and  adEndDate";
		$res = $db->where ( $where )->field ( 'adId,adfile,adurl,adname,adTypes' )->order ( 'adSort ASC' )->select ();
		print_r ( json_encode ( $res ) );
	}
	// 发现页
	public function FaxianAd() {
		$db = M ( 'zidingyi' );
		$where ['type'] = 2;
		$where ['status'] = 1;
		$res = $db->where ( $where )->order ( 'id desc' )->getfield ( 'content' );
		echo html_entity_decode ( $res );
	}
	// 单页广告
	public function singlePageAd() {
		$id = I ( 'pageid' );
		$db = M ( 'ads' );
		$res = $db->where ( array (
				'adId' => $id 
		) )->field ( 'adName,adContent' )->find ();
		$res['adContent']=html_entity_decode($res['adContent']);
		$this->ajaxReturn($res);
	}
	
	// 天使在校园
	public function AngelAd() {
		$db = M ( 'zidingyi' );
		$where ['type'] = 1;
		$where ['status'] = 1;
		$res = $db->where ( $where )->order ( 'id desc' )->getfield ( 'content' );
		echo html_entity_decode ( $res );
	}
	// 登录
	public function login() {
		// 默认状态为
		$res ['status'] = - 1;
		$uname = I ( 'uname' );
		$upwd = I ( 'upwd' );
		$imei=I('imei');
		if (empty ( $uname ) || empty ( $upwd )) {
			print_r ( json_encode ( $res ) );
		}
		$map ['loginName|userEmail|userPhone'] = array (
				'eq',
				$uname 
		);
		$map ['userFlag'] = 1;
		$map ['userStatus'] = 1;
		$map ['userType'] = 0; // 0为用户
		$isExists = M ( 'users' )->where ( $map )->find ();
		if ($isExists) {
			if ($isExists ['loginPwd'] == md5 ( $upwd . $isExists ['loginSecret'] )) {
				// 更新一下用户最后一次登录的信息
				$data = array ();
				$data ['lastTime'] = date ( 'Y-m-d H:i:s' );
				$data ['lastIP'] = get_client_ip ();
				$data ['peImei'] =$imei;
				$m = M ( 'users' );
				$m->where ( " userId=" . $isExists ['userId'] )->data ( $data )->save ();
				// 返回数据
				$isExists ['status'] = 1;
				$isExists ['ip'] = get_client_ip ();
				print_r ( json_encode ( $isExists ) );
			} else {
				print_r ( json_encode ( $res ) );
			}
		} else {
			print_r ( json_encode ( array (
					'status' => - 2 
			) ) );
		}
	}
	// 用户注册
	public function register() {
		// 默认用户名或者密码为空
		$res ['status'] = - 1;
		$data ['userPhone'] = I ( 'phone' );
		$data ['loginPwd'] = I ( 'pwd' );
		$data['peImei']=I('imei');
		$code = I ( 'code' );
		if (! $data ['userPhone'] || ! $data ['loginPwd']) {
			// 用户名密码必填
			print_r ( json_encode ( $res ) );
			return;
		}
		/*
		 * if($code!=$_SESSION['yanzhenma']||$data['userPhone']!=$_SESSION['zhuchephone']){ //手机和接收到的验证码不匹配' print_r(json_encode(array('status'=>-3)));return; }
		 */
		$isExistsPhone = M ( 'users' )->where ( array ('userPhone' => $data ['userPhone'],'userFlag' => 1 ) )->find ();
		if ($isExistsPhone) {
			// 用户已经存在
			print_r ( json_encode ( array (
					'status' => - 2 
			) ) );
			return;
		}
		//查询一元购手机号码是否已经注册
		$phone=$data ['userPhone'];
		$pwd=$data ['loginPwd'];
		$sendDate ['mobile'] = "$phone";
		$sendDate ['createTime'] = Date('Y-m-d H:i:s',time());
		
		$res=$this->postCurl($sendDate, C('YYDB_URL').'checkPhone',C('YYDB_KEY'));
		
		
		if($res!=0){
		    // 用户已经存在
		    print_r ( json_encode ( array (
		        'status' => - 2
		    ) ) );
		    return;
		}
		$data ['createTime'] = date ( 'Y-m-d H:i:s', time () );
		$data ['lastIP'] = get_client_ip ();
		// $data['userName']=$data['userPhone'];
		// $data['loginName']=$data['userPhone'];
		$data ['userStatus'] = 1;
		$data ['userFlag'] = 1;
		$data ['loginSecret'] = mt_rand ( 1000, 9999 );
		$data ['loginPwd'] = md5 ( $data ['loginPwd'] . $data ['loginSecret'] );
		$data ['userType'] = 0;
		M()->startTrans();
		$A=true;
		$B=true;
		$db = M ( 'users' );
		if ($db->create ( $data )) {
			$r = $db->add ();
			if (!$r) {
			    $A=false;
			}
		}
		//注册一元购
		//查询一元购手机号码是否已经注册
		$sendDate ['mobile'] = "$phone";
		$sendDate ['password'] = "$pwd";
		$res=$this->postCurl($sendDate, C('YYDB_URL').'addUser', C('YYDB_KEY'));
	
		if($res!=0){
		    $B=false;
		}
		
		if($A&&$B){
		    M()->commit();
		    $info = $db->where ( array ('userId' => $r ) )->find ();
		    $info ['status'] = 1;
		    print_r ( json_encode ( $info ) );
		}else{
		    M()->rollback();
		    // 注册失败
		    print_r ( json_encode ( array ('status' => 0 ) ) );
		}
		
	}
	// 发送手机验证码
	public function getCode() {
		$ip = get_client_ip ();
		$type = I ( 'type' ) ? I ( 'type' ) : 0; // 如果 为1则为用户注册申请
		$phone = trim ( I ( 'phone' ) );
		// 判断此手机是否已经注册
		if ($type) {
			$r = M ( 'users' )->where ( array (
					'userPhone' => $phone,
					'userFlag' => 1 
			) )->find ();
			if ($r) {
				// 手机号码已经注册
				print_r ( json_encode ( array (
						'status' => - 3 
				) ) );
				return;
			}
		}
		if (! preg_match ( '/^1[3|7|4|5|8]{1}\d{9}$/', $phone )) {
			// 手机号码不正确
			print_r ( json_encode ( array (
					'status' => - 1 
			) ) );
			return;
		}
		$map ['ip'] = $ip;
		$map ['phone'] = $phone;
		$map ['_logic'] = 'OR';
		$time = date ( 'Y-m-d', time () );
		$where ['_complex'] = $map;
		$where ['time'] = $time;
		$exists = M ( 'sendmes' )->where ( $where )->count ();
		if ($exists > 10) {
			// 每天获取的验证码数大于3次限制当天不能再发送
			print_r ( json_encode ( array (
					'status' => - 2 
			) ) );
			return;
		}
		$code = mt_rand ( 100000, 999999 );
		session ( array (
				'name' => 'session_id',
				'expire' => 600 
		) );
		session ( 'yanzhenma', $code );
		session ( 'zhuchephone', $phone );
		$cont = session ( 'yanzhenma' ) . "(点点就到平台验证码,五分钟内有效）【点点就到】";
		$text = $cont;
		$data = array (
				'phone' => $phone,
				'ip' => $ip,
				'info' => $text,
				'time' => $time 
		);
	
		import("Vendor.yunsms");
	    $mes=new\yunsms;
	    $result=$mes->sendMsg($phone, $cont);
		if ($result['status'] == 1) {
			// 短信已经下发
			M ( 'sendmes' )->data ( $data )->add ();
			print_r ( json_encode ( array (
					'status' => 1,
					'yanzhenma' => session ( 'yanzhenma' ),
					'zhuchephone' => session ( 'zhuchephone' ) 
			) ) );
			return;
		} else {
			// 短信发送失败
			print_r ( json_encode ( array (
					'status' => 0 
			) ) );
			return;
		}
	}
	public function Get($url) {
		if (function_exists ( 'file_get_contents' )) {
			$file_contents = file_get_contents ( $url );
		} else {
			$ch = curl_init ();
			$timeout = 5;
			curl_setopt ( $ch, CURLOPT_URL, $url );
			curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
			curl_setopt ( $ch, CURLOPT_CONNECTTIMEOUT, $timeout );
			$file_contents = curl_exec ( $ch );
			curl_close ( $ch );
		}
		return $file_contents;
	}
	// 更改密码
	public function changePwd() {
		// 默认用户名或者密码为空
		$res ['status'] = - 1;
		$map ['userPhone'] = I ( 'phone' );
		$data ['loginPwd'] = I ( 'pwd' );
		if (! $map ['userPhone'] || ! $data ['loginPwd']) {
			// 用户名密码必填
			print_r ( json_encode ( $res ) );
			return;
		}
		$isExistsPhone = M ( 'users' )->where ( array (
				'userPhone' => $map ['userPhone'],
				'userFlag'=>1,
				'userStatus'=>1,
		) )->find ();
		if (! $isExistsPhone) {
			// 用户不存在
			print_r ( json_encode ( array (
					'status' => - 2 
			) ) );
			return;
		}
		$map['userFlag']=1;
		$map['userStatus']=1;
		$data ['lastTime'] = date ( 'Y-m-d H:i:s', time () );
		$data ['lastIP'] = get_client_ip ();
		$data ['loginPwd'] = md5 ( $data ['loginPwd'] . $isExistsPhone ['loginSecret'] );
		$db = M ( 'users' );
		$r = $db->where($map)->save ( $data );
		if ($r !== false) {
			// 修改成功
			$res ['status'] = 1;
			print_r ( json_encode ( $res ) );
			return;
		} else {
			// 修改失败
			$res ['status'] = 0;
			print_r ( json_encode ( $res ) );
			return;
		}
	}
	
	
	// 找回支付密码
	public function findPayPwd() {
	    // 默认用户名或者密码为空
	    $res ['status'] = - 1;
	    $userId=I('userId');
	    $data ['payPwd'] = I ( 'pwd' );
	    if (! $data ['payPwd']) {
	        // 用户名密码必填
	        print_r ( json_encode ( $res ) );
	        return;
	    }
	    
	    $isExistsPhone = M ( 'users' )->where ( array ('userId'=>$userId) )->find ();
	    if (! $isExistsPhone) {
	        // 用户不存在
	        print_r ( json_encode ( array (
	            'status' => - 2
	        ) ) );
	        return;
	    }
	    $data ['lastTime'] = date ( 'Y-m-d H:i:s', time () );
	    $data ['lastIP'] = get_client_ip ();
	    $data ['payPwd'] = md5 ( $data ['payPwd'] . $isExistsPhone ['loginSecret'] );
	    $db = M ( 'users' );
	    $r = $db->where( array ('userId'=>$userId))->save ( $data );
	    if ($r !== false) {
	        // 修改成功
	        $res ['status'] = 1;
	        print_r ( json_encode ( $res ) );
	        return;
	    } else {
	        // 修改失败
	        $res ['status'] = 0;
	        print_r ( json_encode ( $res ) );
	        return;
	    }
	}
	
	
	
	//第三方登录绑定手机号
	public function qqRegisterCode() {
	    $ip = get_client_ip ();
	    $phone = trim ( I ( 'phone' ) );
	    if (!preg_match ( '/^1[3|7|4|5|8]{1}\d{9}$/', $phone )) {
	        // 手机号码不正确
	        print_r ( json_encode ( array ( 'status' => - 1,'msg'=>'手机号码格式不正确' ) ) );
	        return;
	    }
	    $user_exists = M ( 'users' )->where ( array ('userPhone' => $phone, 'userStatus' => 1,'userFlag'=>1) )->find ();
	    if ($user_exists) {
	        print_r ( json_encode ( array ( 'status' => - 3,'msg'=>'手机号码已被占用' ) ) );
	        return;
	    }
	    $map ['ip'] = $ip;
	    $map ['phone'] = $phone;
	    $map ['_logic'] = 'OR';
	    $time = date ( 'Y-m-d', time () );
	    $where ['_complex'] = $map;
	    $where ['time'] = $time;
	    $exists = M ( 'sendmes' )->where ( $where )->count ();
	    if ($exists > 10) {
	        // 每天获取的验证码数大于3次限制当天不能再发送
	        print_r ( json_encode ( array ( 'status' => - 2,'msg'=>'今天发送的短信过多') ) );
	        return;
	    }
	    $code = mt_rand ( 100000, 999999 );
	    $cont = $code. "(点点就到平台验证码,五分钟内有效）【点点就到】";
	    $data = array (
	        'phone' => $phone,
	        'ip' => $ip,
	        'info' => $cont,
	        'time' => $time
	    );
	
	    import("Vendor.yunsms");
	    $mes=new\yunsms;
	    $result=$mes->sendMsg($phone, $cont);
	    if ($result['status'] == 1) {
	        // 短信已经下发
	        M ( 'sendmes' )->data ( $data )->add ();
	        print_r ( json_encode ( array ('status' => 1,'yanzhenma' =>$code,'zhuchephone' => $phone,'msg'=>'短信发送成功！') ) );
	        return;
	    } else {
	        // 短信发送失败
	        print_r ( json_encode ( array ('status' => -1,'msg'=>'短信发送失败！') ) );
	        return;
	    }
	}
	
	//第三方登录时绑定手机
	public  function registerBindPhone(){
	    $userPhone=I('phone','0');
	    $loginPwd=I('loginPwd');
	    $loginType=I('loginType');//wx微信登录,qq-》qq登录
	    $openId=I('uniqueId');
	     //判断手机是否被注册
	    $isRegister=M('users')->where(array('userFlag'=>1,'userStatus'=>1,'userPhone'=>$userPhone))->find();
	    if($isRegister){ print_r(json_encode(array('status'=>'-1','msg'=>'手机号已被注册！')));exit();} 
	    $isExists=array();
	    
         if($loginType=='wx'){
                $isExists=M('users')->where(array('userFlag'=>1,'userStatus'=>1,'weixinLogin'=>$openId))->find();
            }else if($loginType=='qq'){
                $isExists=M('users')->where(array('userFlag'=>1,'userStatus'=>1,'qqLogin'=>$openId))->find();
            }
            
            if(!$isExists){
                //不存在此用户或者用户已经绑定过手机
                print_r(json_encode(array('status'=>'-1','msg'=>'请返回重新授权登录')));exit();
            }
            $loginSecret=$isExists['loginSecret'];
            if(empty($isExists['loginSecret'])){
                $loginSecret=mt_rand(1000,9999);
            } 
            $saveInfo=array();
            $saveInfo['userPhone']=$userPhone;
            $saveInfo['loginSecret']=$loginSecret;
            $saveInfo['loginPwd']=md5($loginPwd.$loginSecret);
            $rs=M('users')->where(array('userId'=>$isExists['userId']))->save($saveInfo);
            if($rs!=false){
                $isExists['status']=1;
                $isExists['userPhone']=$userPhone;
                $isExists['msg']='资料信息绑定成功！';
                print_r(json_encode($isExists));exit();
            }else{
                print_r(json_encode(array('status'=>'-1','msg'=>'请返回重新授权登录')));exit();
            }
	}
	
	
	// 获取修改手机的号的验证码
	// 发送手机验证码
	public function getChangeCode() {
		$ip = get_client_ip ();
		$phone = trim ( I ( 'phone' ) );
		if (! preg_match ( '/^1[3|7|4|5|8]{1}\d{9}$/', $phone )) {
			// 手机号码不正确
			print_r ( json_encode ( array (
					'status' => - 1 
			) ) );
			return;
		}
		$user_exists = M ( 'users' )->where ( array (
				'userPhone' => $phone,
				'userStatus' => 1,
		       'userFlag'=>1
		) )->find ();
		if (! $user_exists) {
			// 用户不存在
			print_r ( json_encode ( array (
					'status' => - 3 
			) ) );
			return;
		}
		if ($user_exists)
			$map ['ip'] = $ip;
		$map ['phone'] = $phone;
		$map ['_logic'] = 'OR';
		$time = date ( 'Y-m-d', time () );
		$where ['_complex'] = $map;
		$where ['time'] = $time;
		$exists = M ( 'sendmes' )->where ( $where )->count ();
		if ($exists > 10) {
			// 每天获取的验证码数大于3次限制当天不能再发送
			print_r ( json_encode ( array (
					'status' => - 2 
			) ) );
			return;
		}
		$code = mt_rand ( 100000, 999999 );
		session ( array (
				'name' => 'session_id',
				'expire' => 600 
		) );
		session ( 'yanzhenma', $code );
		session ( 'zhuchephone', $phone );
		$cont = session ( 'yanzhenma' ) . "(点点就到平台验证码,五分钟内有效）【点点就到】";
		$text = $cont;
		$data = array (
				'phone' => $phone,
				'ip' => $ip,
				'info' => $text,
				'time' => $time 
		);

		import("Vendor.yunsms");
	    $mes=new\yunsms;
	    $result=$mes->sendMsg($phone, $cont);
		if ($result['status'] == 1) {
			// 短信已经下发
			M ( 'sendmes' )->data ( $data )->add ();
			print_r ( json_encode ( array (
					'status' => 1,
					'yanzhenma' => session ( 'yanzhenma' ),
					'zhuchephone' => session ( 'zhuchephone' ) 
			) ) );
			return;
		} else {
			// 短信发送失败
			print_r ( json_encode ( array (
					'status' => 0 
			) ) );
			return;
		}
	}
	
	// 修改昵称
	public function changeNiChen() {
		$res ['status'] = - 1;
		$map ['userId'] = I ( 'userid' );
		$map ['userName'] = I ( 'username' );
		$r = M ( 'users' )->data ( $map )->save ();
		if ($r != false) {
			$res = M ( 'users' )->where ( array (
					'userId' => $map ['userId'] 
			) )->find ();
			$res ['status'] = 0;
			print_r ( json_encode ( $res ) );
		} else {
			print_r ( json_encode ( $res ) );
		}
	}
	// 绑定手机
	public function bindPhone() {
		$autologin = I ( 'autologin' );
		$data ['qqLogin|weixinLogin|weiboLogin'] = array (
				'eq',
				$autologin 
		);
		$isExs = M ( 'users' )->where ( $data )->find ();
		if ($isExs) {
			$map ['userPhone'] = I ( 'phone' );
			$res = M ( 'users' )->where ( $data )->save ( $map );
			if ($res != false) {
				// 绑定成功
				echo json_encode( array (
						'status' => 0 
				) );
			} else {
				// 绑定失败
				echo json_encode( array (
						'status' => - 1 
				) );
			}
		} else {
			// 用户没登录
			echo json_encode( array (
					'status' => - 2 
			) );
		}
	}
	// 上传图片
	public function uploadImg() {
		if (IS_POST) {
			$uid = I ( 'userid' ) ? I ( 'userid' ) : I ( 'get.userid' );
			header ( "Content-Type: text/html; charset=UTF-8" );
			// vendor(\uploadImage::max_file_size);
			import ( 'Vendor.uploadImage' );
			$username = $_GET ['username'];
			// $file,$destination="",$name="",$dbPath="",$update=0
			$i = new \uploadImage ( $_FILES ['filename'], './Upload/touxiang/', $username, 'Upload/touxiang/' );
			$i->imageStart ();
			if ($i->imageStauts == 1) {
				// echo '头像设置成功';
				$data ['userId'] = $uid;
				$data ['userPhoto'] = $i->iamgePath;
				$res = M ( 'users' )->data ( $data )->save ();
				echo $i->iamgePath;
			} else {
			}
		} else {
			$this->display ( 'Index/uploadImg' );
		}
	}
	// 保存用户信息
	public function saveUserInfo() {
		if (IS_POST) {
			$userid = I ( 'userid' );
			$identity = I ( 'identity' );
			$truename = I ( 'truename' );
			$school = I ( 'school' );
			$stuno = I ( 'stuno' );
			$data ['userId'] = $userid;
			$data ['trueName'] = $truename;
			$data ['identity'] = $identity;
			$data ['school'] = $school;
			$data ['stuNo'] = $stuno;
			$res = M ( 'users' )->data ( $data )->save ();
			if ($res != false) {
				$data ['status'] = 0;
				echo json_encode( $data );
			} else {
				echo json_encode( array (
						'status' => - 1 
				) );
			}
		} else {
			echo json_encode( array (
					'status' => - 1 
			) );
		}
	}
	// 用户的地址
	public function myAddress() {
		$userid = I ( 'userid' );
		if (! $userid) {
			// 非法请求
			echo json_encode( array (
					'status' => - 1 
			) );
			return;
		}
		$field = "addressId,userName,userPhone,userTel,address,userSex,latitude,longitude";
		$res = M ( 'user_address' )->field ( $field )->where ( array (
				'userId' => $userid 
		) )->select ();
		if ($res) {
			echo json_encode( $res ); // json_encode($res);
		} else {
			// 还没有地址
			echo json_encode( array (
					'status' => - 1 
			) );
		}
	}
	// 获取单条地址信息
	public function myAddressById() {
		$addrid = I ( 'addrid' );
		$field = "addressId,userName,userPhone,userTel,address,userSex";
		$res = M ( 'user_address' )->where ( array (
				'addressId' => $addrid 
		) )->field ( $field )->find ();
		if ($res) {
			echo json_encode( $res );
		} else {
			// 无数据
			echo json_encode( array (
					'status' => - 1 
			) );
		}
	}
	// 保存用户更改的信息
	public function saveUserAddress() {
		$userid = I ( 'userid' );
		$addrid = I ( 'addrid' );
		$data ['userId'] = $userid;
		$data ['addressId'] = $addrid;
		$data ['userPhone'] = I ( 'phone' );
		$data ['userName'] = I ( 'username' );
		$data ['address'] = I ( 'address' );
		$data ['userSex'] = I ( 'sex' );
		if (! $userid || ! $addrid) {
			// 条件不对
			echo json_encode( array (
					'status' => - 1 
			) );
			return;
		}
		$res = M ( 'user_address' )->save ( $data );
		if ($res != false) {
			// 保存成功
			echo json_encode( array (
					'status' => 0 
			) );
		} else {
			// 保存失败
			echo json_encode( array (
					'status' => - 2 
			) );
		}
	}
	// 添加新的地址
	public function addUserAddress() {
		$userid = I ( 'userid' );
		$data ['userId'] = $userid;
		$data ['userPhone'] = I ( 'phone' );
		$data ['userName'] = I ( 'username' );
		$data ['address'] = I ( 'address' );
		$data ['userSex'] = I ( 'sex' );
		$data ['latitude'] = I ( 'latitude' );
		$data ['longitude'] = I ( 'longitude' );
		$data ['createTime'] = date ( 'Y-m-d H:i:s', time () );
		if (! $userid) {
			// 条件不对
			echo json_encode( array (
					'status' => - 1 
			) );
			return;
		}
		$db = M ( 'user_address' );
		if ($db->create ( $data ) != false) {
			$res = $db->add ();
			if ($res) {
				// 添加成功
				echo json_encode( array (
						'status' => 0 
				) );
			} else {
				// 添加失败
				echo json_encode( array (
						'status' => - 2 
				) );
			}
		} else {
			echo json_encode( array (
					'status' => - 2 
			) );
		}
	}
	// 检测是否绑定了手机号码
	public function isBindPhone() {
		$userid = I ( 'userid' );
	}
	// 首次登录设置登录 密码
	public function initSetPwd() {
		$userid = I ( 'userid' );
		$pwd = I ( 'pwd' );
		if (! $userid || ! $pwd) {
			echo json_encode( array (
					'status' => - 1 
			) );
			return;
		}
		$db = M ( 'users' );
		$data ['loginSecret'] = mt_rand ( 1000, 9999 );
		$data ['loginPwd'] = md5 ( $pwd . $data ['loginSecret'] );
		$res = $db->where ( array (
				'userId' => $userid 
		) )->save ( $data );
		if ($res != false) {
			echo json_encode( array (
					'status' => 0 
			) );
		} else {
			echo json_encode( array (
					'status' => - 1 
			) );
		}
	}
	// 首次登录设置支付密码
	public function initSetPayPwd() {
		$userid = I ( 'userid' );
		$pwd = I ( 'pwd' );
		if (! $userid || ! $pwd) {
			echo json_encode( array (
					'status' => - 1 
			) );
			return;
		}
		$db = M ( 'users' );
		$loginSecret = M ( 'users' )->where ( array (
				'userId' => $userid 
		) )->getfield ( 'loginSecret' );
		$data ['payPwd'] = md5 ( $pwd . $loginSecret );
		$res = $db->where ( array (
				'userId' => $userid 
		) )->save ( $data );
		if ($res != false) {
			echo json_encode( array (
					'status' => 0 
			) );
		} else {
			echo json_encode( array (
					'status' => - 1 
			) );
		}
	}
	// 重置密码
	public function resetPwd() {
		$userid = I ( 'userid' );
		$pwd = I ( 'pwd' );
		$yuanpwd = I ( 'yuanpwd' );
		if (! $userid || ! $pwd) {
			echo json_encode( array ('status' => - 1 ) );
			return;
		}
		
		$db = M ( 'users' );
		$loginSecret = M ( 'users' )->where ( array ('userId' => $userid) )->find ();
	
		if (md5 ( $yuanpwd . $loginSecret ['loginSecret'] ) != $loginSecret ['loginPwd']) {
			echo json_encode( array ('status' => - 2) );
			return;
		}
		$A=true;
		$B=true;
		//更新一元守宝的密码
		$phone=$loginSecret['userPhone'];
		$sendDate ['password'] = "$pwd";
		$sendDate ['mobile'] = "$phone";
		$sendDate ['createTime'] = Date('Y-m-d H:i:s',time());
		$res=$this->postCurl($sendDate, C('YYDB_URL').'editUser',C('YYDB_KEY'));
		if($res!=0){
		    $A=false;
		}
		M()->startTrans();
		$data ['loginPwd'] = md5 ( $pwd . $loginSecret ['loginSecret'] );
		$res = $db->where ( array ('userId' => $userid ) )->save ( $data );
		if(!$res){
		    $B=false;
		}
		if ($res &&$B) {
		    M()->commit();
			echo json_encode( array ('status' => 0 ) );
		} else {
		    M()->rollback();
			echo json_encode( array ('status' => - 1) );
		}
	}
	
	// 重置支付密码
	public function resetPayPwd() {
		$userid = I ( 'userid' );
		$pwd = I ( 'pwd' );
		$yuanpwd = I ( 'yuanpwd' );
		if (! $userid || ! $pwd) {
			echo json_encode( array (
					'status' => - 1 
			) );
			return;
		}
		$db = M ( 'users' );
		$loginSecret = M ( 'users' )->where ( array (
				'userId' => $userid 
		) )->find ();
		if (md5 ( $yuanpwd . $loginSecret ['loginSecret'] ) != $loginSecret ['payPwd']) {
			echo json_encode( array (
					'status' => - 2 
			) );
			return;
		}
		$data ['payPwd'] = md5 ( $pwd . $loginSecret ['loginSecret'] );
		$res = $db->where ( array (
				'userId' => $userid 
		) )->save ( $data );
		if ($res != false) {
			echo json_encode( array (
					'status' => 0 
			) );
		} else {
			echo json_encode( array (
					'status' => - 1 
			) );
		}
	}
	
	// 获取系统配置信息
	public function getCs() {
		$map ['fieldCode'] = array (
				'eq',
				array (
						'phoneNo',
						'qqNo' 
				) 
		);
		$sql = "select  fieldValue from oto_sys_configs where fieldCode='phoneNo'  or fieldCode='qqNo'  order by configid desc ";
		$res = M ()->query ( $sql );
		echo json_encode( array (
				'phone' => $res [1] ['fieldValue'],
				'qq' => $res [0] ['fieldValue'] 
		) );
	}
	
	// 获取热门问题等
	public function getHotQuestion() {
		$field = 'catId,catName';
		$res = M ( 'article_cats' )->where ( array (
				'isShow' => 1 
		) )->field ( $field )->select ();
		echo json_encode( $res );
	}
	// 每个问题的列表
	public function questList() {
		$catid = I ( 'catid' );
		$field = "articleTitle,articleId";
		$res = M ( 'articles' )->where ( array (
				'catId' => $catid 
		) )->field ( $field )->select ();
		echo json_encode( $res );
	}
	// 问题详情
	public function questDetail() {
		$catid = I ( 'catid' );
		$res = M ( 'articles' )->where ( array (
				'articleId' => $catid 
		) )->getField ( 'articleContent' );
		echo json_encode( html_entity_decode ( $res ) );
	}
	// 建议
	public function suggest() {
		$userid = I ( 'userid' );
		$content = I ( 'content' );
		$phone = I ( 'phone' );
		if ($userid) {
			$db = M ( 'suggest' );
			$data ['u_id'] = $userid;
			$data ['cellphone'] = $phone;
			$data ['content'] = $content;
			if ($db->create ( $data )) {
				$r = $db->add ();
				if ($r) {
					echo json_encode( array (
							'status' => 0 
					) );
				} else {
					echo json_encode( array (
							'status' => - 1 
					) );
				}
			}
		} else {
			echo json_encode( array (
					'status' => - 1 
			) );
		}
	}
	// 商城入驻协议
	public function protocol() {
		$res = M ( 'sys_configs' )->where ( array (
				'fieldCode' => 'protocol' 
		) )->getField ( 'fieldValue' );
		echo json_encode( $res );
	}
	
	// 加盟图片上传
	// 上传图片
	public function toJoinUploadImg() {
		if (IS_POST) {
			$uid = I ( 'userid' ) ? I ( 'userid' ) : I ( 'get.userid' );
			$imgType = I ( 'imgtype' ) ? I ( 'imgtype' ) : I ( 'get.imgtype' );
			// $imgType为1营业执行，2身份证正面，3，身份证反面
			header ( "Content-Type: text/html; charset=UTF-8" );
			// vendor(\uploadImage::max_file_size);
			import ( 'Vendor.uploadImage' );
			$username = $_GET ['username'];
			// $file,$destination="",$name="",$dbPath="",$update=0
			$i = new \uploadImage ( $_FILES ['filename'], './Upload/toJoin/', $username, 'Upload/toJoin/' );
			$i->imageStart ();
			if ($i->imageStauts == 1) {
				// echo '头像设置成功';
				/*
				 * $data['userId']=$uid; if($imgType==1){ $data['permitImg']=$i->iamgePath; $res=M('users')->data($data)->save(); }else if($imgType==2){ $data['identityImg']=$i->iamgePath; $res=M('users')->data($data)->save(); }else if($imgType==3){ $data['identityRevImg']=$i->iamgePath; $res=M('users')->data($data)->save(); }
				 */
				echo $i->iamgePath;
			} else {
			}
		} else {
			$this->display ( 'Index/uploadImg' );
		}
	}
	// 商户入驻
	public function toJoin() {
		$data ['userId'] = I ( 'userid' );
		$isExis = M ( 'shops' )->where ( array (
				'userId' => $data ['userId'] 
		) )->find ();
		if ($isExis) {
			echo json_encode( array (
					'status' => - 2,
					'mess' => '你已经申请过了，请等待审核' 
			) );
			return;
		}
		
		$data ['shopCompany'] = I ( 'shopname' );
		$data ['shopName'] = I ( 'shopname' );
		$data ['goodsCatId1'] = I ( 'sort' );
		$data ['shopImg'] = 'Upload/shops/default_shop_ico.jpg';
		$data ['shopAddress'] = I ( 'shopAddr' );
		$data ['shopTel'] = I ( 'phone' );
		$data ['identityNo'] = I ( 'identity' );
		$data ['permitNo'] = I ( 'permit' );
		$data ['identityImg'] = I ( 'identity_zhen' );
		$data ['identityRevImg'] = I ( 'identity_fan' );
		$data ['permitImg'] = I ( 'permitimg' );
		$data ['areaId1'] = I ( 'province' );
		$data ['areaId2'] = I ( 'city' );
		$data ['areaId3'] = I ( 'area' );
		$data ['email'] = I ( 'email' );
		$data ["shopStatus"] = 0;
		$data ["shopAtive"] = 1;
		$data ["shopFlag"] = 1;
		$data ["createTime"] = date ( 'Y-m-d H:i:s' );
		$data ["serviceStartTime"] = 9;
		$data ["serviceEndTime"] = 23;
		$data ["shopSn"] = mt_rand ( 10000, 99999 );
		$data ["isInvoice"] = 0;
		$data ["userName"] = I ( 'name' );
		$data ["latitude"] = I ( 'latitude' );
		$data ["longitude"] = I ( 'longitude' );
		$db = M ( 'shops' );
		if ($db->create ( $data ) != false) {
			$res = $db->add ();
			if ($res) {
				M ( 'users' )->where ( array (
						'userId' => I ( 'userid' ) 
				) )->setField ( array (
						'bizPhone' => I ( 'phone' ),
						'isBiz' => 1 
				) ); // 设置商家登录
				                                                             // 申请成功
				echo json_encode( array (
						'status' => 0,
						'mess' => '资料己提交，请等待审核！' 
				) );
			} else {
				echo json_encode( array (
						'status' => - 1,
						'mess' => '申请失败，请填写完整资料' 
				) );
			}
		} else {
			echo json_encode( array (
					'status' => - 1,
					'mess' => '申请失败，请填写完整资料' 
			) );
		}
	}
	// 获取省
	public function getCity() {
		$m = M ( 'areas' );
		$parentid = I ( 'parentId' ) ? I ( 'parentId' ) : 0;
		$map ['areaFlag'] = 1;
		// $map['isShow']=1;
		$field = "areaId,areaName";
		$map ['parentId'] = $parentid;
		$res = $m->where ( $map )->field ( $field )->select ();
		echo json_encode( $res );
	}
	// 判断是否已经申请过商家加盟
	public function isExistsToJoin() {
		$userid = I ( 'userid' ) ? I ( 'userid' ) : I ( 'get.userid' );
		$isExis = M ( 'shops' )->where ( array (
				'userId' => $userid 
		) )->find ();
		if ($isExis) {
			if ($isExis ['shopStatus'] == 1) {
				echo json_encode( array (
						'status' => 1,
						'mess' => '你己经是商家！' 
				) );
			} else if ($isExis ['shopStatus'] == 0) {
				echo json_encode( array (
						'status' => 2,
						'mess' => '你已经申请过了，请等待审核' 
				) );
			} else if ($isExis ['shopStatus'] == - 1) {
				echo json_encode( array (
						'status' => 3,
						'mess' => '申请被拒绝' 
				) );
			}
		} else {
			echo json_encode( array (
					'status' => 0,
					'mess' => '可以申请！' 
			) );
		}
	}
	// 店铺分类
	public function getShopCats() {
		$shopId = I ( 'shopid' );
		$parentId = 0;
		$m = M ( 'shops_cats' );
		$res = $m->where ( 'shopId=' . $shopId . ' and catFlag=1 and isShow=1 and parentId=' . $parentId . " and shopId=" . $shopId )->order ( 'catSort asc ' )->select ();
		echo json_encode( $res );
	}
	// 店铺产品列表
	public function getProductByCat() {
		$shopId = I ( 'shopid' );
		$page = I ( 'page' ) ? I ( 'page' ) : 0;
		$catid = (int)I ( 'catid',0);
		if($catid=='undefined'){
		    $catid=0;
		}
		if ($catid) {
			$where = " and g.shopCatId1=$catid  ";
		}else{
	        $parentId = 0;
		    $m = M ( 'shops_cats' );
		    $res = $m->where ( 'shopId=' . $shopId . ' and catFlag=1 and isShow=1 and parentId=' . $parentId . " and shopId=" . $shopId )->order ( 'catSort asc ' )->select ();
	        $catid=$res[0]['catId'];
			if($catid){
			  $where = " and g.shopCatId1=$catid  ";	
			}
		}
		//$limit = 30;
		//$page = $page * $limit;
		$sql = "select g.goodsId,g.goodsSn,g.goodsName,g.goodsImg,g.marketPrice,g.goodsThums,g.goodsUnit,g.shopPrice,g.goodsStock,g.saleCount,g.isSale,g.isRecomm,g.isHot,g.isBest,g.isNew,ga.isRecomm as attIsRecomm from __PREFIX__goods g
				left join __PREFIX__goods_attributes ga on g.goodsId = ga.goodsId and ga.isRecomm = 1
				where g.goodsFlag=1
		     and g.shopId=" . $shopId . " and g.goodsStatus=1 and g.isSale=1  $where ";
		$sql .= " order by g.goodsId desc";
		//$sql .= " order by g.goodsId desc  limit $page,$limit ";
		$res = M ()->query ( $sql );
		echo json_encode( $res );
	}
	
	
	//红包
	public function houbao(){
	    $userId=I('userid',0);
	    $okMoney=I('okMoney',0);
	    if(!$userId||$okMoney<=0){
	        echo json_encode(array());return;
	    }
	    //首单红包
	    $isFirst=M('orders')->where(array('userId'=>$userId,'redId'=>array('gt',0)))->find();
	    $time=time();
	    if(!$isFirst){
	        $first=M('red')->where(array('isDel'=>1,'isFirst'=>1,'_string'=>"$time>=startTime and endTime>=$time",'redUp'=>array('elt',$okMoney)))->select();
	        foreach ($first as $k=>$v){
	            $first[$k]['check']=1;
	            $first[$k]['startTime']=date('Y-m-d',$v['startTime']);
	            $first[$k]['endTime']=date('Y-m-d',$v['endTime']);
	        }
	        $first_f=M('red')->where(array('isDel'=>1,'isFirst'=>1,'_string'=>"$time>=startTime and endTime>=$time",'redUp'=>array('gt',$okMoney)))->select();
	        foreach ($first_f as $k=>$v){
	            $first_f[$k]['check']=0;
	            $first_f[$k]['startTime']=date('Y-m-d',$v['startTime']);
	            $first_f[$k]['endTime']=date('Y-m-d',$v['endTime']);
	        }
	    }
		
	    //普通 红包
	    $common=M('red')->where(array('isDel'=>1,'isFirst'=>0,'_string'=>"$time>=startTime and endTime>=$time",'redUp'=>array('elt',$okMoney)))->select();
	    foreach ($common as $k=>$v){
	        $common[$k]['check']=1;
	        $common[$k]['startTime']=date('Y-m-d',$v['startTime']);
	        $common[$k]['endTime']=date('Y-m-d',$v['endTime']);
	    }
	    $common_f=M('red')->where(array('isDel'=>1,'isFirst'=>0,'_string'=>"$time>=startTime and endTime>=$time",'redUp'=>array('gt',$okMoney)))->select();
	    foreach ($common_f as $k=>$v){
	        $common_f[$k]['check']=0;
	        $common_f[$k]['startTime']=date('Y-m-d',$v['startTime']);
	        $common_f[$k]['endTime']=date('Y-m-d',$v['endTime']);
	    }
	    $temp=array($first,$common,$first_f,$common_f);
	    $newArr=array();
	    $flag=false;
	    foreach ($temp as $v){
	       if(is_array($v)){
	           if(!$flag){
	               $flag=true;
	               $newArr=$v;
	           }else{
	               $newArr=array_merge($newArr,$v);
	           }
	       }
	    }
	    echo json_encode($newArr);
	}
	
	//下单自动选择平台后台 
	public function palfRed(){
	    $money=I('money',0);
	    $userid=I('userid',0);
	    $time=time();
	    $First=false;
	    if($userid){
	        $First=M('orders')->where(array('userId'=>$userid))->find();
	    }
	    $redArr=array();
	    if($First){
	        $where['isFirst']=0;
	    }
	    $field='id,redUp,redReduce,isFirst';
	    $where['isDel']=1;
	    $time=time();
	    $where['_string']="$time>=startTime and endTime>=$time";
	    $redFirst=M('red')->where($where)->field($field)->order('redUp ASC')->select();
	    $key=$this->nearRed($money, $redFirst);
	   echo json_encode($redFirst[$key]);

	}
	
	//查找最接近的优惠平台红包key
	public function nearRed($m,$coupon){
	    //$maxKey = array_search(max($coupon),$coupon);
	    $maxKey=count($coupon)-1;
	    foreach($coupon as $k=> $v){
	        if($k==$maxKey){
	            if($m>=$coupon[$maxKey]['redUp']){
	                return $k;
	            }
	        }else{
	            if($m>=$v['couponUp']&&$m<$coupon[$k+1]['redUp']){
	                return $k;
	            }
	        }
	    }
	     
	}
	
	
	
	//查询是否是首次下单
	public function checkFirstRed(){
	    $userid=I('userid',0);
	    if(!$userid){
	        echo json_encode(array('status'=>0));return;
	    }
	    //$First=M('orders as o')->join('oto_red as r on r.id=o.redId and r.isFirst=1')->whrer(array('o.userId'=>$userid))->find();
	    $First=M('orders')->where(array('userId'=>$userid))->find();
	    if($First){
	        echo json_encode(array('status'=>1));
	    }else{
	        echo json_encode(array('status'=>0));
	    }
	}

	//平台最小红包展示 
	
	public function minRed(){
	    $userid=I('userid',0);
	    $First=false;
	    if($userid){
	        $First=M('orders')->where(array('userId'=>$userid))->find();
	    }
	    $field='id,redUp,redReduce,isFirst';
	    $where['isDel']=1;
	    $where['isFirst']=1;
	    $time=time();
	    $where['_string']="$time>=startTime and endTime>=$time";
	    $redFirst=M('red')->where($where)->field($field)->order('redUp ASC')->find();
	    //判断是否首次下单
	    if($First){
	        $redFirst['first']=1;
	    }else{
	        $redFirst['first']=0;
	    }
	    echo json_encode($redFirst);
	}
	
	
	//平台所有红包列表
	public function redList(){
	    $field='id,redUp,redReduce';
	    $where['isDel']=1;
	    $where['isFirst']=1;
	    $time=time();
	    $where['_string']="$time>=startTime and endTime>=$time";
	    $redFirst=M('red')->where($where)->field($field)->order('redUp ASC')->select();
	    
	    $where['isFirst']=0;
	    $redMore=M('red')->where($where)->field($field)->order('redUp ASC')->select();
	    
	    echo json_encode(array('first'=>$redFirst,'more'=>$redMore));
	}
	
	
	//自动算优惠卷
	public function maxCoupon(){
	    $shopId=I('shopId');
	    $money=I('money');
	    $userid=I('userid');
	    if(!$shopId){
	        return;
	    }
	    $time=time();
	   
	    $ids='';
	    $useIds=M('orders as o')->where(array('o.userId'=>$userid,'o.shopId'=>$shopId,'o.couponId'=>array('gt',0)))->join('oto_coupon as c  on o.couponId=c.id and c.isFirst=1')->field('o.couponId')->select();
		foreach ($useIds as $v){
	        $ids.=$v['couponId'].',';
	    }
	    $ids=rtrim($ids,',');
	    
	    if($ids){
	        $map['id']=array('not in',$ids);
	    }
	    $map['shopId']=$shopId;
	    $map['isDel']=1;
	    $map['_string']="startTime<=$time and endTime>=$time";
	    
	    $coupon=M('coupon')->where($map)->field('couponUp,couponReduce,id,isFirst')->order('couponUp ASC')->select();
	
		$key=$this->nearCoupon($money, $coupon);
	    if($coupon[$key]['isFirst']==1){
	        $isUse=M('orders')->where(array('userId'=>$userid,'couponId'=>$coupon[$key]['id']))->find();
	        if($isUse){
	            return;
	        }else{
	            echo json_encode($coupon[$key]);
	        }
	    }else{
	        echo json_encode($coupon[$key]);
	    }
	}
	
	//查找最接近的优惠key
	public function nearCoupon($m,$coupon){
		//$maxKey = array_search(max($coupon),$coupon); 
	    $maxKey=count($coupon)-1;
	    foreach($coupon as $k=> $v){
	        if($k==$maxKey){
                if($m>=$coupon[$maxKey]['couponUp']){
                    return $k;
                }
	        }else{
	            if($m>=$v['couponUp']&&$m<$coupon[$k+1]['couponUp']){
	                return $k;
	            }
	        }
	    }
	    
	}
	
	// 店铺信息
	public function getShopInfo() {
		$shopId = I ( 'shopid' );
		$field = "shopId,psMode,shopName,deliveryFreeMoney,shopAtive,shopImg,shopFlag,latitude,longitude,serviceStartTime,serviceEndTime,serviceStartTime2,serviceEndTime2,shopTel,deliveryStartMoney,deliveryCostTime,deliveryFreeMoney,deliveryMoney,shopAddress";
		$res = M ( 'shops' )->where ( array (
				'shopId' => $shopId 
		) )->field ( $field )->find ();
		$time=time();
		$res['coupon']=M('coupon')->where(array('shopId'=>$res['shopId'],'isDel'=>1,'_string'=>"startTime<=$time and endTime>=$time"))->field('couponUp,couponReduce,isFirst')->order('couponUp ASC')->select();
		$tempP=explode(',', $res['psMode']);
		$ps='';
		if(in_array(1, $tempP)){
		    $ps="自提";
		}
		if(in_array(2, $tempP)){
		    if($ps=='自提'){
		        $ps.=";商家配送";
		    }else{
		        $ps="商家配送";
		    }
		}
		$res['psFangShi']=$ps;
		$S1=$res['serviceStartTime'];
		$E1=$res['serviceEndTime'];
		$S2=$res['serviceStartTime2'];
		$E2=$res['serviceEndTime2'];
		$H=intval(date('G'));
		$status=false;
		if($S1>$E1){
		    if($H>=$S1){//当前时间大于开始时间
		        $status=true;
		    }else if($E1>$H) {//结束时间大于当前时间
		        $status=true;
		    }
		}else{
		    //当前时间在开始和结束之间
		        if($S1==0&&$E1==0){
		            
		        }else{
		            if($H>=$S1&&$H<$E1){
		                $status=true;
		            }
		        }
		}
		
		if(!$status){
		    if($S2>$E2){
		        if($H>=$S2){//当前时间大于开始时间
		            $status=true;
		        }else if($E2>$H) {//结束时间大于当前时间
		            $status=true;
		        }
		    }else{
		        //当前时间在开始和结束之间
		        if($S2==0&&$E2==0){
		    
		        }else{
		            if($H>=$S2&&$H<$E2){
		                $status=true;
		            }
		        }
		    }
		}
	
		
		//营业时间
		if($status){
		    $res['shopTime']=1;
		}else{
		    $res['shopTime']=0;
		}
		
		if ($res ['shopAtive'] == 0 || $res ['shopFlag'] == 0) {
			$res ['shopOpen'] = 0;
		} else {
			$res ['shopOpen'] = 1;
		}
		
		$res['serviceStartTime2']=intval($res['serviceStartTime2']);
		$res['serviceEndTime2']=intval($res['serviceEndTime2']);
		
		echo json_encode( $res );
	}
	
	
	/**
	 * 添加商品到购物车(ajax)
	 */
	public function addToCartAjax() {
		$m = D ( 'Wap/Cart' );
		$res = $m->addToCart ();
		echo "{status:1}";
	}
	
	// 用户最新一条收货地址
	// 用户的地址
	public function LastAddress() {
		$userid = I ( 'userid' );
		if (! $userid) {
			// 非法请求
			echo json_encode( array (
					'status' => - 1 
			) );
			return;
		}
		$field = "addressId,userName,userPhone,userTel,address,userSex";
		$res = M ( 'user_address' )->field ( $field )->where ( array (
				'userId' => $userid 
		) )->order ( 'addressId desc' )->find ();
		if ($res) {
			echo json_encode( $res ); // json_encode($res);
		} else {
			// 还没有地址
			echo json_encode( array (
					'status' => - 1 
			) );
		}
	}
	// 根据Id获取收货地址
	public function getAddrByid() {
		$addrid = I ( 'addrid' );
		if (! $addrid) {
			// 非法请求
			echo json_encode( array (
					'status' => - 1 
			) );
			return;
		}
		$field = "addressId,userName,userPhone,userTel,address,userSex";
		$res = M ( 'user_address' )->field ( $field )->where ( array (
				'addressId' => $addrid 
		) )->find ();
		if ($res) {
			echo json_encode( $res ); // json_encode($res);
		} else {
			// 还没有地址
			echo json_encode( array (
					'status' => - 1 
			) );
		}
	}
	//下单
	public function submitOrder() {
		$shopid = I ( 'shopid' );
		$userid = I ( 'userid' );
		$username = I ( 'username' );
		$deliveryType = I ( 'deliveryType' );
		$payway = I ( 'payway' );
		$address = I ( 'address' );
		$userphone = I ( 'userphone' );
		$isself = I ( 'isself' );
		//$info = $this->object2array ( html_entity_decode ( I ( 'data' ) ) );
		$info=json_decode($_POST['data'],true);
		$totalmoney = 0;
		$couid=I('couid',0);//商家优惠卷
        $redid=I('redid',0);//红包
        $longitude=I('longitude',0);
        $latitude=I('latitude',0);
        
		if(!$shopid||!$userid){
		     $this->ajaxReturn(array('status'=>-2,'msg'=>'数据异常'));
		     return;
		}
		if(!$longitude||!$latitude){
		    $this->ajaxReturn(array('status'=>-3,'msg'=>'定位失败！'));return;
		}
		
		if(empty($info)){
		    $this->ajaxReturn(array('status'=>-4,'msg'=>'数据异常'));return;
		}
		
		// 店铺信息
		$field = "isPack,packFree,deliveryType,shopFlag,shopStatus,shopName,shopImg,latitude,longitude,serviceStartTime,serviceEndTime,deliveryStartMoney,deliveryFreeMoney,deliveryMoney,shopAddress";
		
		$shopinfo = M ( 'shops' )->where ( array ('shopId' => $shopid ) )->field ( $field )->find ();
		if(empty($shopinfo)||$shopinfo['shopFlag']!=1||$shopinfo['shopStatus']!=1){
		    $this->ajaxReturn(array('status'=>-7,'msg'=>'店铺状态异常'));return;
		}
		
		//判断库存
		
	    //判断是否已经断货
		$id_num=array();
		$ids=array();
		$checkInfo=true;//检测商品ID是否有异常
		foreach ( $info as $k => $v ) {
		    $ids[$k]=(int)$v['id'];
		    if(!$v['id']){
		        $checkInfo=false;
		    }
		    $id_num[$k]['id']=$v['id'];
		    $id_num[$k]['num']=$v ['num']?$v ['num']:1;
			//$totalmoney += $v ['num'] * $v ['price'];
		}
		
		if(!$checkInfo){
		    $this->ajaxReturn(array('status'=>-5,'msg'=>'商品数据异常'));return;
		}
		
		$goodsField='goodsStock,goodsId';
	    $goodsInfo=M('goods')->where(array('goodsId'=>array('in',$ids))) ->field($goodsField)->select();
	    
	    if(empty($goodsInfo)){
	        $this->ajaxReturn(array('status'=>-6,'msg'=>'提交空订单'));return;
	    }
	    
		//缺货产品和实际库存
		$oos=array();
		$i=0;
		foreach ($goodsInfo as $k=>$v){
		      foreach($id_num as $kk=>$vv){
		         if($vv['id']==$v['goodsId']){
		             if($v['goodsStock']<$vv['num']){
		                 $oos[$i]['id']=$v['goodsId'];
		                 $oos[$i]['num']=$v['goodsStock'];
		                 $i++;
		             }
		         }
		      }
		}
	    if(count($oos)>0){
	        $this->ajaxReturn($oos);
	        return;
	    }

		//判断库存结束
		//打包费
	    $pickFee=0;
	    
	    //商品总价
		foreach ( $info as $k => $v ) {
		    $shopPrice=M('goods')->where(array('goodsId'=>$v['id']))->getField('shopPrice');
		    $totalmoney+=$shopPrice*$v['num'];
		    $pickFee+=$v['num']*$shopinfo['packFree'];
		}
		
		if($shopinfo['isPack']==0){
		    $pickFee=0;
		}
		
		$redMoney=0;
		$couponMoney=0;
		$time=time();
		//判断红包
		 if($redid){
			    $redInfo= M('red')->where(array('isDel'=>1,'id'=>$redid,'_string'=>"$time>=startTime and endTime>=$time",'redUp'=>array('elt',$totalmoney)))->find();
			     if($redInfo){
			         $redMoney=$redInfo['redReduce'];
			     }else{
			         $redid=0;
			     }
			}
		//判断商家优惠卷
		if($couid){
		    $couponInfo=M('coupon')->where(array('shopId'=>$shopid,'id'=>$couid,'isDel'=>1,'_string'=>"startTime<=$time and endTime>=$time",'couponUp'=>array('elt',$totalmoney)))->find();
		    if($couponInfo){
		        $couponMoney=$couponInfo['couponReduce'];
		    }else{
		        $couid=0;
		    }
		}
		
	
		
		
		// 根据距离 算配送费
		//距离
		$distance=$this->getDistance($latitude,$longitude,$shopinfo['latitude'],$shopinfo['longitude']);
		
		$postFree=1;//收配送费
		
		if($totalmoney>$shopinfo['deliveryFreeMoney']){
		    $postFree=0;
		}
		$where=array();
		$where['isDel']=0;
		$where['_string']=" $distance >=lower_limit and $distance<=upper_limit";
		$deliveryMoney=M('delivery')->where($where)->order('delivery_money ASC')->getField('delivery_money');
		if(!$deliveryMoney){
		    $this->ajaxReturn(array('status'=>-8,'msg'=>'不在配送范围！'));
		}
		
		$m = M ( 'orderids' );
		$orderSrcNo = $m->add ( array (
				'rnd' => microtime ( true ) 
		) );
		$orderNo = $orderSrcNo . "" . (fmod ( $orderSrcNo, 7 ));
		// 创建订单信息
		$data = array ();
		$data ["orderNo"] = $orderNo;
		$data ["shopId"] = $shopid;
		$deliverType = $deliveryType;
		$data ["userId"] = $userid;
		$data ["orderFlag"] = 1;
		$data ["totalMoney"] = $totalmoney;
		$data['postFree']=1;
		//判断经纬度
		if ($isself == 1 or $isself==-1) { // 自提或者不用配送
			$deliveryMoney = 0;
		    $data['postFree']=0;//0包邮，1需要配送费，主要用于商家结算
		} else {
		     //按经纬度算出来的邮费;
			//$deliverMoney = ($totalmoney < $shopinfo ["deliveryFreeMoney"]) ? $shopinfo ["deliveryMoney"] : 0;
		    if($totalmoney>=$shopinfo ["deliveryFreeMoney"]){
		        $data['postFree']=0;//满多少免邮
		    }
		}
		
		$data ["deliverMoney"] = $deliveryMoney;
		$data ["payType"] = $payway;
		$data ["packFee"] = $pickFee;
		$data ["deliverType"] = $deliverType;
		$data ["userName"] = $username;
		$data ["areaId1"] = 0;
		$data ["areaId2"] = 0;
		$data ["areaId3"] = 0;
		$data ["communityId"] = 0;
		$data ["userAddress"] = $address;
		$data ["userTel"] = '';
		$data ["userPhone"] = $userphone;
		$data ['orderScore'] = round ( $data ["totalMoney"] + $data ["deliverMoney"], 0 );
		$data ["isInvoice"] = 0;
		$data ["orderRemarks"] = '';
		$data ["requireTime"] = date ( 'Y-m-d H:i:s', time () );
		$data ["invoiceClient"] = '';
		$data ["isAppraises"] = 0;
		$data ["isSelf"] = $isself;
		$data ["redId"] = $redid;//红包
		$data ["couponId"] = $couid;//优惠卷ID
		//包邮
		if($data['postFree']==0){
		    $data ["needPay"] = $totalmoney -$redMoney-$couponMoney+$pickFee;
		}else{
		    $data ["needPay"] = $totalmoney + $deliveryMoney-$redMoney-$couponMoney+$pickFee;
		}
		
		$data ["createTime"] = date ( "Y-m-d H:i:s" );
		if ($payway == 1) { // 在线支付
			$data ["orderStatus"] = - 2;
		} else {
			// 自提
			$data ["orderStatus"] = 0;
		}
		$data ["orderunique"] = time ();
		$data ["isPay"] = 0;
		$morders = M ( 'orders' );
		$orderId = $morders->add ( $data );
		if ($orderId) {
			// orderId订单表的ID
			echo json_encode( array (
					'status' => 0,
					'orderNo' => $orderId,
					'orderNumber' => $orderNo,
					'totalMoney' => $data ["needPay"],
			    'msg'=>'订单提交成功'
			) );
		} else {
			echo json_encode( array (
					'status' => - 1 ,'msg'=>'订单提交失败'
			) );
		}
		// 订单创建成功则建立相关记录
		if ($orderId > 0) {
			$orderIds [] = $orderId;
			// 建立订单商品记录表
			$mog = M ( 'order_goods' );
			foreach ( $info as $key => $sgoods ) {
				$data = array ();
				$data ["orderId"] = $orderId;
				$data ["goodsId"] = $sgoods ["id"];
				$data ["goodsAttrId"] = 0;
				$data ["goodsNums"] = $sgoods ["num"];
				$data ["goodsPrice"] = $sgoods ["price"];
				$data ["goodsName"] = $sgoods ["name"];
				$data ["goodsThums"] = '';
				$mog->add ( $data );
			}
			if ($payway == 0) {
				// 建立订单记录
				$data = array ();
				$data ["orderId"] = $orderId;
				$data ["logContent"] = ($deliveryType ["deliverType"] == 0) ? "下单成功" : "下单成功等待审核";
				$data ["logUserId"] = $userid;
				$data ["logType"] = 0;
				$data ["logTime"] = date ( 'Y-m-d H:i:s' );
				$mlogo = M ( 'log_orders' );
				$res = $mlogo->add ( $data );
				// 建立订单提醒
				$sql = "SELECT userId,shopId,shopName FROM oto_shops WHERE shopId=$shopid AND shopFlag=1 ";
				$users = M ()->query ( $sql );
				$morm = M ( 'order_reminds' );
				for($i = 0; $i < count ( $users ); $i ++) {
					$data = array ();
					$data ["orderId"] = $orderId;
					$data ["shopId"] = $shopid;
					$data ["userId"] = $users [$i] ["userId"];
					$data ["userType"] = 0;
					$data ["remindType"] = 0;
					$data ["createTime"] = date ( "Y-m-d H:i:s" );
					$morm->add ( $data );
				}
				/*  
				// 修改库存
				foreach ( $info as $key => $sgoods ) {
					$sql = "update __PREFIX__goods set goodsStock=goodsStock-" . $sgoods ['num'] . " where goodsId=" . $sgoods ["id"];
					M ()->query ( $sql );
				} */
			} else {
				$data = array ();
				$data ["orderId"] = $orderId;
				$data ["logContent"] = "订单已提交，等待支付";
				$data ["logUserId"] = $userid;
				$data ["logType"] = 0;
				$data ["logTime"] = date ( 'Y-m-d H:i:s' );
				$mlogo = M ( 'log_orders' );
				$mlogo->add ( $data );
			}
		}
	}
	public function test() {
		return;
		M('tixian')->where(array('bankId'=>0))->setField(array('isdel'=>1));
		print_r(M('tixian')->select());
		return;
		echo date('Y-m-d H:i:s',1461081600);
		return;
		$str="2016/4/20";
		echo strtotime($str);
		return;
		
		$str = date ( 'Y-m-d H:i:s', time () );
		
		p ( $str );
		p ( strtotime ( $str ) );
		return;
		$type = $out_trade_no [0];
		$sql = "";
		if ($type == 'A') { // 单笔还款
			$out_trade_no = ltrim ( $out_trade_no, 'A' );
			$sql = "select * from oto_repayment where id=$out_trade_no";
		} else if ($type == "B") { // 全部还款
			$out_trade_no = ltrim ( $out_trade_no, 'B' );
			$ids = '';
			$temp = explode ( '_', $out_trade_no );
			foreach ( $temp as $k => $v ) {
				$ids .= $v . ',';
			}
			$ids = rtrim ( $ids, ',' );
			$sql = "select * from oto_repayment where id in ($ids)";
		} else {
			echo 'fail';
			return;
		}
		echo $sql;
	}
	function object2array(&$object) {
		$object = json_decode ( $object, true );
		return $object;
	}
	// 获取用户余额
	public function getUserbalance() {
		$userid = I ( 'userid' );
		$res = M ( 'users' )->where ( array (
				'userId' => $userid 
		) )->getField ( 'userMoney' );
		$pwd = M ( 'users' )->where ( array (
				'userId' => $userid 
		) )->getField ( 'payPwd' );
		// 是否有支付密码
		if ($pwd) {
			$pwd = 1;
		} else {
			$pwd = 0;
		}
		if (isset ( $res )) {
			echo json_encode( array (
					'status' => 0,
					'balance' => $res,
					'payPwd' => $pwd 
			) );
		} else {
			echo json_encode( array (
					'status' => - 1,
					'balance' => 0 
			) );
		}
	}
	// 余额支付
	public function goPay() {
		$payPwd = I ( 'payPwd' );
		$orderNo = I ( 'orderNo' );
		
		//检测营业时间
		//订单状态   //检测订单是否已付款
		$orderInfo=M('orders')->where(array('orderId'=>$orderNo))->find();
		if($orderInfo['isPay']==1){
		    $this->ajaxReturn(array('status'=>-6,'msg'=>'订单状态已改变'));return;
		}
		//店铺状态
		$shopInfo=M('shops')->where(array('shopId'=>$orderInfo['shopId']))->find();
		if($shopInfo['shopFlag']!=1||$shopInfo['shopStatus']!=1){
		    $this->ajaxReturn(array('status'=>-3,'msg'=>'店铺状态异常！'));return;
		}
		//检查营业时间
		$S1=$shopInfo['serviceStartTime'];
		$E1=$shopInfo['serviceEndTime'];
		$S2=$shopInfo['serviceStartTime2'];
		$E2=$shopInfo['serviceEndTime2'];
		$H=intval(date('G'));
		$status=false;
		if($S1>$E1){
		    if($H>=$S1){//当前时间大于开始时间
		        $status=true;
		    }else if($E1>$H) {//结束时间大于当前时间
		        $status=true;
		    }
		}else{
		    //当前时间在开始和结束之间
		    if($S1==0&&$E1==0){
		         
		    }else{
		        if($H>=$S1&&$H<$E1){
		            $status=true;
		        }
		    }
		}
		if(!$status){
		    if($S2>$E2){
		        if($H>=$S2){//当前时间大于开始时间
		            $status=true;
		        }else if($E2>$H) {//结束时间大于当前时间
		            $status=true;
		        }
		    }else{
		        //当前时间在开始和结束之间
		        if($S2==0&&$E2==0){
		             
		        }else{
		            if($H>=$S2&&$H<$E2){
		                $status=true;
		            }
		        }
		    }
		}
		//休息中，或者非店铺营业时间
		if(!$status||$shopInfo['shopAtive'] == 0){
		    if(!$status){
		        $this->ajaxReturn(array('status'=>-4,'msg'=>'非营业时间！'));return;
		    }
		    if($shopInfo['shopAtive'] == 0){
		        $this->ajaxReturn(array('status'=>-5,'msg'=>'店铺打烊啦！'));return;
		    }
		}
		
		$userid = I ( 'userid' );
		$uinfo = M ( 'users' )->where ( array (
				'userId' => $userid 
		) )->find ();
		if (md5 ( $payPwd . $uinfo ['loginSecret'] ) != $uinfo ['payPwd']) {
			// 支付密码错
			echo json_encode( array (
					'status' => - 2 ,'msg'=>'支付密码错误'
			) );
			return;
		}
		$orderNumber=M('orders')->where(array('orderId'=>$orderNo))->getField('orderNo');
		$ispay=M('orders')->where(array('orderId'=>$orderNo))->getField('isPay');
		if($ispay==1){
			echo json_encode( array ('status' => 0,'msg'=>'订单已经付款' ) );
			return;
		}
		$payMoney = I ( 'payMoney' );
		$payType = I ( 'payType' );
		$payTime = date ( 'Y-m-d H:i:s' );
		if (! $orderNo || ! $userid || ! $payMoney || ! isset ( $payType ) || $orderNo == 'undefined' || $userid == 'undefined' || $payMoney == 'undefined') {
			echo json_encode( array (
					'status' => - 1 ,'msg'=>'数据异常'
			) );
			return;
		}
			M ()->startTrans ();
			$this->checkStock($orderNo,0,0);
			// 减去用户的钱
			$r = M ( 'users' )->where ( array (
					'userId' => $userid 
			) )->setDec ( 'userMoney', $payMoney );
			// 更改订单状态为已付款
			$a = M ( 'orders' )->where ( array (
					'orderId' => $orderNo 
			) )->setField ( array (
					'isPay' => 1,
					'payType' => 0,
					'paytime' => time () 
			) );
			if ($r && $a) {
				$userinfo = M ( 'users' )->where ( array (
						'userId' => $userid 
				) )->find ();
				$orderInfo = M ( 'orders' )->where ( array (
						'orderId' => $orderNo 
				) )->find ();
				// 添加积分和消费记录
				$this->OperationMoneyRecord ( 1, $payMoney, $orderNumber, 0, $userid, $userinfo ['userMoney'],'',0);
				$this->OperationScoreRecord ( 1, $orderInfo ['shopId'], $payMoney, $orderNo, 1, $userid );
				// M('users')->where(array('userId'=>$userid))->setInc('userScore',round ( $payMoney ));
			
		
				//极光推送->手机号
				/* $bizPhone=M('users')->join('as u left join oto_shops as s on u.userId=s.userId')->where(array('s.shopId'=>$orderInfo['shopId']))->getFiel('u.bizPhone');
				echo $bizPhone;*/
				
			  $bizInfo = M ( 'users' )->where ( array (
							's.shopId' => $orderInfo ['shopId'] 
					) )->join ( 'as u left join oto_shops as s on u.userId=s.userId' )->field ( 'u.bizPhone' )->find ();
				
				M ()->commit ();
				
				  echo json_encode( array (
			      'status' => 0,'bizPhone'=>$bizInfo['bizPhone'],'orderNumber'=>$orderNumber,'msg'=>'支付成功！'
					) );
				
				if($bizInfo){
				    $this->pushtouser($bizInfo['bizPhone']);
				   /*
				   try {
				        $this->sendMessToBiz($bizInfo['bizPhone'],$orderNumber);
				        $this->sendMessToBiz('15115431966',$orderNumber);
				    } catch (Exception $e) {
				    }
					*/

				}
				return;
			} else {
				M ()->rollback ();
				echo json_encode( array (
				'status' => -1,'msg'=>'支付失败'
				) );
			}
	
	}
	// 获取订单信息
	public function getOrderInfo() {
		$orderNo = I ( 'orderNo' );
		$field = "t.username as tname,s.shopTel,s.userName as sname,s.userName as csname,t.telephone,o.isRefund,o.isRefundHandle,o.orderNo,o.shopId,o.orderStatus,o.signTime,o.totalMoney,o.deliverMoney,o.signTime,o.needPay,o.isSelf,o.payType,o.isPay,o.userId,o.userName,o.signTime,o.userPhone,o.userAddress,o.orderScore,o.createTime,o.packFee,o.postFree";
		$res = M ( 'orders' )->field ( $field )->where ( array (
				'orderId' => $orderNo 
		) )->join('as o left join oto_staff as t on t.id=staff_Id left join oto_shops as s on s.shopId=o.shopId ')->find ();
		$tousu=0;
		$pinjia=0;
		if(time()-strtotime($res['createTime'])>604800){//7天的
			$tousu=1;
			$pinjia=1;
		}
		$pinjia = M ( 'goods_sun' )->where ( array (
				'orderNo' => $orderNo 
		) )->count ();
		$tousu=M('complain')->where(array('ordersn'=>$orderNo))->count();
		if($res['receiving']){
			if(time()-$res['receiving']>604800){
				$tousu=1;
			}
		}
		$pinjia = $pinjia ? $pinjia : 0;
		$tousu = $tousu ? $tousu : 0;
		$res ['pinjiaStatus'] = $pinjia;
		$res['tousu']=$tousu;
		if($res['signTime']){
			$res['signTime']=date('Y-m-d H:i:s',$res['signTime']);
		}
		echo json_encode( $res );
	}
	// 店铺信息
	public function getShopInfoByOrderId() {
		$orderNo = I ( 'orderNo' );
		$shopId = M ( 'orders' )->where ( array (
				'orderId' => $orderNo 
		) )->getField ( 'shopId' );
		$field = "shopId,shopTel,shopName,qqNo,shopImg,latitude,longitude,serviceStartTime,serviceEndTime,deliveryStartMoney,deliveryFreeMoney,deliveryMoney,shopAddress";
		$res = M ( 'shops' )->where ( array (
				'shopId' => $shopId 
		) )->field ( $field )->find ();
		echo json_encode( $res );
	}
	// 获取 订单里商品的列表
	public function getOrderProductList() {
		$orderNo = I ( 'orderNo' );
		$res = M ( 'order_goods' )->where ( array (
				'orderId' => $orderNo 
		) )->select ();
		echo json_encode( $res );
	}
	// 投诉订单
	public function touSu() {
		$orderNo = I ( 'orderNo' );
		$type = I ( 'type' );
		$info = M ( 'orders' )->field ( 'userName,shopId' )->where ( array (
				'orderId' => $orderNo 
		) )->find ();
		$content = I ( 'content' );
		$data ['username'] = $info ['userName'];
		$data ['user_id'] = $info ['shopId'];
		$data ['ordersn'] = $orderNo;
		$data ['type'] = $type;
		$data ['content'] = $content;
		$data ['time'] = time ();
		$db = M ( 'complain' );
		if ($db->create ( $data ) != false) {
			$res = $db->add ();
			if ($res) {
				echo json_encode( array (
						'status' => 0 
				) );
			} else {
				echo json_encode( array (
						'status' => - 1 
				) );
			}
		} else {
			echo json_encode( array (
					'status' => - 1 
			) );
		}
	}
	// 评价商品
	public function comment() {
		$shopdata = $this->object2array ( html_entity_decode ( I ( 'shopdata' ) ) );
		$gooddata = $this->object2array ( html_entity_decode ( I ( 'gooddata' ) ) );
		$orderNo = I ( 'orderNo' );
		$userid = I ( 'userid' );
		$orderINfo=M ( 'orders' )->where ( array (
				'orderId' => $orderNo 
		) )->field ( 'userName,needPay' )->find();
		// 店铺评分
		$data [0] ['orderNo'] = $orderNo;
		$data [0] ['user_id'] = I ( 'shopid' );
		$data [0] ['shopname'] = I ( 'shopname' );
		$data [0] ['username'] = $orderINfo['userName'];
		$data [0] ['time'] = time ();
		$data [0] ['goodsname'] = '';
		$data [0] ['goods_id'] = '';
		$data [0] ['attitude'] = $shopdata [0] ['pinFen'];
		$data [0] ['assess'] = '';
		$data [0] ['content'] = $shopdata [0] ['content'];
		// 商品评分数据
		foreach ( $gooddata as $k => $v ) {
			$data [$k + 1] ['orderNo'] = $orderNo;
			$data [$k + 1] ['user_id'] = I ( 'shopid' );
			$data [$k + 1] ['shopname'] = I ( 'shopname' );
			$data [$k + 1] ['username'] = $data [0] ['username'];
			$data [$k + 1] ['time'] = time ();
			$data [$k + 1] ['goodsname'] = $v ['goodsName'];
			$data [$k + 1] ['goods_id'] = $v ['goodid'];
			$data [$k + 1] ['attitude'] = $data [0] ['attitude'];
			$data [$k + 1] ['assess'] = $v ['assess'];
			$data [$k + 1] ['content'] = $v ['content'];
		}
		// 批量添加
		$res = M ( 'goods_sun' )->addAll ( $data );
		if ($res) {
			echo json_encode( array (
					'status' => 0 
			) );
			$this->OperationScoreRecord ( 6, I ( 'shopid' ), $orderINfo['needPay'], $orderNo, 1, $userid );
		} else {
			echo json_encode( array (
					'status' => - 1 
			) );
		}
	}
	// 用户订单
	public function getUserOrder() {
		$userid = I ( 'userid' );
		$page = I ( 'page' ) ? I ( 'page' ) : 0;
		$limit = 30;
		$start = $page * $limit;
		$sql = "select b.shopImg,b.shopName,a.orderId,a.isRefundHandle,a.orderNo,a.shopId,a.isRefund,a.orderStatus,a.payType,a.isSelf,a.isPay,a.totalMoney,a.needPay, a.userName,a.userAddress,a.createTime,a.signTime ,( select count(id) from oto_order_goods where oto_order_goods.orderId=a.orderId) as totalNum,(select count(id) from oto_goods_sun where oto_goods_sun.orderNo=a.orderId ) as pinJiaStatus from oto_orders as a
left join oto_shops as b on a.shopId=b.shopId  where a.userId=$userid and a.isDel=0 order by a.orderId desc limit  $start,$limit  ";
		$res = M ()->query ( $sql );
		foreach ($res as $k=>$v){
			$res[$k]['signTime']=date('Y-m-d H:i:s',$res[$k]['signTime']);
			if(time()-strtotime($v['createTime'])>604800){//如果大于7天，不能再评
				$res[$k]['pinJiaStatus']=1;
			}
		}
		echo json_encode( $res );
	}
	
	//用户点击确认订单
	public  function  confirmOrder(){
		 $userid=I('userid');
		 $orderid=I('orderid');
		 $orderInfo=M('orders')->where(array('orderId'=>$orderid,'userId'=>$userid))->field('shopId,needPay,orderStatus,isRefund,redId')->find();
		 M()->startTrans();
		 if($orderInfo['orderStatus']==-5||$orderInfo['isRefund']==2){
		 	echo json_encode(array('status'=>-2));return;//订单已退款成功
		 }
		 $a=M('orders')->where(array('orderId'=>$orderid,'userId'=>$userid))->setField(array('orderStatus'=>4,'isRefund'=>0,'signTime'=>time()));
		 if($orderInfo['orderStatus']==-3||$orderInfo['isRefund']==1){//有申请退款等操作的，则处理退款表
		 	$b=M('refund')->where(array('orderid'=>$orderid))->setField('isconfirm',1);
		 	$c=M('shops')->where(array('shopId'=>$orderInfo['shopId']))->setInc('money',$orderInfo['needPay']);
		 	if($a!==false&&$b!==false&&$c){
		 		M()->commit();
		 		echo json_encode(array('status'=>0));return;
		 	}else{
		 		M()->rollback();
		 		echo json_encode(array('status'=>-1));return;
		 	}
		 }
		 $redMoney=0;
		 if($orderInfo['redId']>0){
		 	$redMoney=M('red')->where(array('id'=>$orderInfo['redId']))->getField('redReduce');
		 }
		 $c=M('shops')->where(array('shopId'=>$orderInfo['shopId']))->setInc('money',$orderInfo['needPay']+$redMoney);
		 if($a!==false&&$c){
		 	M()->commit();
		 	echo json_encode(array('status'=>0));
		 }else{
		 	M()->rollback();
		 	echo json_encode(array('status'=>-1));
		 }
	}
	
	// 用户删除订单
	public function delOrderById() {
		$orderid = I ( 'orderid' );
		$userid = I ( 'userid' );
		$map ['orderId'] = $orderid;
		$map ['userId'] = $userid;
		// $map['_string']='orderStatus=4 or orderStatus=-2 or orderStatus=0';
		$res = M ( 'orders' )->where ( $map )->setField ( 'isDel', 1 );
		if ($res != false) {
			echo json_encode( array (
					'status' => 0 
			) );
		} else {
			echo json_encode( array (
					'status' => - 1 
			) );
		}
	}
	//商城分类
	public function getShopSort(){
		$res=M('goodsCats')->where(array('catFlag'=>1))->field('catId,catName')->select();
		echo json_encode($res);
	}
	
	
	//首页店铺列表
	// 附近3公里的店铺营业中的订单
	public function indexShopList() {
	    // 店铺分类
	    $shopSort = I ( 'shopsort' ) ? I ( 'shopsort' ) : 0;
	    // 第几页
	    $page = I ( 'page' );
	    // 经度
	    $longitude = I ( 'longitude' );
	    // 纬度
	    $latitude = I ( 'latitude' );
	    // 排序
	    $order = I ( 'order' ) ? I ( 'order' ) : 'sales';
	    if (! $longitude || ! $latitude || $latitude == 'undefined' || $longitude == 'undefined') {
	        // 获取位置失败
	        echo json_encode( array (
	            'status' => - 1
	        ) );
	        return;
	    }
	    $where = "";
	    if ($shopSort && $shopSort != 'undefined') {
	        $where = " and goodsCatId1= $shopSort ";
	    }
	    $orderby = " ORDER BY shopId DESC ";
	    switch ($order) {
	        case 'new' :
	            $orderby = " ORDER BY shopId DESC ";
	            break; // 默认按店铺ID
	        case 'dist' :
	            $orderby = " ORDER BY  juli ASC ";
	            break; // 距离
	        case 'qisongjia' :
	            $orderby = " ORDER BY deliveryStartMoney ASC ";
	            break; //
	        case 'sales' :
	            $orderby = " ORDER BY monthNum DESC ";
	            break;
	    }
	    $limit = 30;
	    $start = $page * $limit;
	  
$newSql=<<<Eof
SELECT
	*
FROM
	(
		SELECT
			shopId,
			longitude,
			latitude,
			shopStatus,
			shopAtive,
			goodsCatId1,
			shopName,
			shopImg,
			deliveryStartMoney,
			deliveryFreeMoney,
			deliveryMoney,
			deliveryCostTime,
			serviceStartTime,
			serviceEndTime,
			serviceStartTime2,
			serviceEndTime2,
			ROUND(
				6378.138 * 2 * ASIN(
					SQRT(
						POW(
							SIN(
								(
									$latitude * PI() / 180 - latitude * PI() / 180
								) / 2
							),
							2
						) + COS($latitude * PI() / 180) * COS(latitude * PI() / 180) * POW(
							SIN(
								(
									$longitude * PI() / 180 - longitude * PI() / 180
								) / 2
							),
							2
						)
					)
				) * 1000
			) AS juli,
			(
				SELECT
					count(orderId)
				FROM
					oto_orders
				WHERE
					isPay = 1
				AND oto_orders.shopId = oto_shops.shopId
			) AS monthNum,
			(
				SELECT
					AVG(attitude)
				FROM
					oto_goods_sun
				WHERE
					user_id = oto_shops.shopId
			) AS avgPinFen
		FROM
			oto_shops
		WHERE
			shopStatus = 1
		AND shopAtive = 1
		AND shopFlag = 1
		AND (
			(
				CASE
				WHEN serviceStartTime <= serviceEndTime THEN
					(
						CASE
						WHEN serviceStartTime = 0
						AND serviceEndTime = 0 THEN
							FALSE
						WHEN serviceStartTime <= HOUR (now())
						AND HOUR (now()) < serviceEndTime THEN
							TRUE
						ELSE
							FALSE
						END
					)
				WHEN serviceStartTime > serviceEndTime THEN
					(
						CASE
						WHEN HOUR (now()) >= serviceStartTime
						OR HOUR (now()) < serviceEndTime THEN
							TRUE
						ELSE
							FALSE
						END
					)
					END
			) or(
				
					CASE
				WHEN serviceStartTime2 <= serviceEndTime2 THEN
					(
						CASE
						WHEN serviceStartTime2 = 0
						AND serviceEndTime2 = 0 THEN
							FALSE
						WHEN serviceStartTime2 <= HOUR (now())
						AND HOUR (now()) < serviceEndTime2 THEN
							TRUE
						ELSE
							FALSE
						END
					)
				WHEN serviceStartTime2 > serviceEndTime2 THEN
					(
						CASE
						WHEN HOUR (now()) >= serviceStartTime2
						OR HOUR (now()) < serviceEndTime2 THEN
							TRUE
						ELSE
							FALSE
						END
					)
					END
			)
		) 
$where	) AS a
WHERE 
	a.shopStatus = 1
AND a.shopAtive = 1 
$orderby LIMIT $start,$limit
Eof;
        $couponDB=M('coupon');
        $time=time();
	    $info = M ()->query ( $newSql );
	    foreach ($info as $k=>$v){
	        $info[$k]['serviceStartTime2']=intval($v['serviceStartTime2']);
	        $info[$k]['serviceEndTime2']=intval($v['serviceEndTime2']);
	        $info[$k]['coupon']=$couponDB->where(array('shopId'=>$v['shopId'],'isDel'=>1,'_string'=>"startTime<=$time and endTime>=$time"))->field('couponUp,couponReduce,isFirst')->order('couponUp ASC')->select();
	        //计算好评率
	        if(empty($v['avgPinFen'])){
	            $info[$k]['avgPinFen']=100;
	            $info[$k]['feng']=sprintf("%0.1f",5);;
	        }else{
	            $info[$k]['feng']=sprintf("%0.1f",$info[$k]['avgPinFen']);
	            $info[$k]['avgPinFen']=round(($v['avgPinFen']/5)*100);
	        }
	    }
	    echo json_encode( $info );
	}
	
	
	
	
	// 附近3公里的店铺营业中的订单
	public function shopList() {
		// 店铺分类
		$shopSort = I ( 'shopsort' ) ? I ( 'shopsort' ) : 0;
		// 第几页
		$page = I ( 'page' );
		// 经度
		$longitude = I ( 'longitude' );
		// 纬度
		$latitude = I ( 'latitude' );
		// 排序
		$order = I ( 'order' ) ? I ( 'order' ) : 'sales';
		if (! $longitude || ! $latitude || $latitude == 'undefined' || $longitude == 'undefined') {
			// 获取位置失败
			echo json_encode( array (
					'status' => - 1 
			) );
			return;
		}
		$where = "";
		if ($shopSort && $shopSort != 'undefined') {
			$where = " and goodsCatId1= $shopSort ";
		}
		$orderby = " ORDER BY monthNum DESC ";
		switch ($order) {
			case 'new' :
				$orderby = " ORDER BY shopId DESC ";
				break; // 默认按店铺ID
			case 'dist' :
				$orderby = " ORDER BY  juli ASC ";
				break; // 距离
			case 'qisongjia' :
				$orderby = " ORDER BY deliveryStartMoney ASC ";
				break; //
			case 'sales' :
				$orderby = " ORDER BY monthNum DESC ";
				break;
		}
		// hour(curtime())>=serviceStartTime and hour(curtime())<= serviceEndTime 
		$limit = 30;
		$start = $page * $limit;
		$sql = "select * from (SELECT shopId,longitude,latitude,shopStatus,shopAtive,goodsCatId1,shopName,shopImg,deliveryStartMoney,deliveryFreeMoney,deliveryMoney,deliveryCostTime,serviceStartTime,serviceEndTime,serviceStartTime2,serviceEndTime2,
ROUND(6378.138*2*ASIN(SQRT(POW(SIN(($latitude*PI()/180-latitude*PI()/180)/2),2)+COS($latitude*PI()/180)*COS(latitude*PI()/180)*POW(SIN(($longitude*PI()/180-longitude*PI()/180)/2),2)))*1000) AS juli
,(SELECT count(orderId) FROM oto_orders WHERE  isPay=1 and oto_orders.shopId=oto_shops.shopId) as monthNum,(select AVG(attitude) from oto_goods_sun where user_id=oto_shops.shopId) as avgPinFen  FROM oto_shops where shopStatus=1 and shopAtive=1 and shopFlag=1 
  and 
  (	
	(
				CASE
				WHEN serviceStartTime <= serviceEndTime THEN
					(
						CASE
						WHEN serviceStartTime = 0
						AND serviceEndTime = 0 THEN
							FALSE
						WHEN serviceStartTime <= HOUR (now())
						AND HOUR (now()) < serviceEndTime THEN
							TRUE
						ELSE
							FALSE
						END
					)
				WHEN serviceStartTime > serviceEndTime THEN
					(
						CASE
						WHEN HOUR (now()) >= serviceStartTime
						OR HOUR (now()) < serviceEndTime THEN
							TRUE
						ELSE
							FALSE
						END
					)
					END
			) or(
				
					CASE
				WHEN serviceStartTime2 <= serviceEndTime2 THEN
					(
						CASE
						WHEN serviceStartTime2 = 0
						AND serviceEndTime2 = 0 THEN
							FALSE
						WHEN serviceStartTime2 <= HOUR (now())
						AND HOUR (now()) < serviceEndTime2 THEN
							TRUE
						ELSE
							FALSE
						END
					)
				WHEN serviceStartTime2 > serviceEndTime2 THEN
					(
						CASE
						WHEN HOUR (now()) >= serviceStartTime2
						OR HOUR (now()) < serviceEndTime2 THEN
							TRUE
						ELSE
							FALSE
						END
					)
					END
			)
	
	)
   $where ) as a where a.  juli < {$this->juli}  and a.shopStatus=1 and a.shopAtive=1
 $orderby LIMIT $start,$limit";
 // a.  juli <10000  and
 
		$info = M ()->query ( $sql );
	    $couponDB=M('coupon');
        $time=time();
		$info = M ()->query ( $sql );
		
		foreach ($info as $k=>$v){
		    $info[$k]['offLine']=0;
		    $info[$k]['serviceStartTime2']=intval($v['serviceStartTime2']);
		    $info[$k]['serviceEndTime2']=intval($v['serviceEndTime2']);
		    $info[$k]['coupon']=$couponDB->where(array('shopId'=>$v['shopId'],'isDel'=>1,'_string'=>"startTime<=$time and endTime>=$time"))->field('couponUp,couponReduce,isFirst')->order('couponUp ASC')->select();
		    //计算好评率
		    if(empty($v['avgPinFen'])){
		        $info[$k]['avgPinFen']=100;
		        $info[$k]['feng']=sprintf("%0.1f",5);;
		    }else{
		        $info[$k]['feng']=sprintf("%0.1f",$info[$k]['avgPinFen']);
		        $info[$k]['avgPinFen']=round(($v['avgPinFen']/5)*100);
		    }
		}
		
		//数量少于50条的，全部在线离线数据都加载出来
		if(count($info)<30){
		    $offLine=$this->OffLineListShop($shopSort,$longitude,$latitude,$order);//在线商店不足50条，则加载非营业时间段的店铺50条
		    
		    if($info){
		        $info=array_merge($info,$offLine);
		    }else{
		        $info=$offLine;
		    }
		}

		echo json_encode( $info );
	}
	// 附近3公里的非营业中的订单
	public function OffLineListShop($shopSort,$longitude,$latitude,$order) {
		// 店铺分类
		//$shopSort = I ( 'shopsort' ) ? I ( 'shopsort' ) : 0;
		$shopSort=$shopSort?$shopSort:0;
		// 第几页
		//$page = I ( 'page' );
		// 经度
		//$longitude = I ( 'longitude' );
		// 纬度
		//$latitude = I ( 'latitude' );
		// 排序
		$order = $order?$order: 'sales';
		if (! $longitude || ! $latitude || $latitude == 'undefined' || $longitude == 'undefined') {
			// 获取位置失败
			echo json_encode( array (
					'status' => - 1 
			) );
			return;
		}
		$where = "";
		if ($shopSort && $shopSort != 'undefined') {
			$where = " and goodsCatId1= $shopSort ";
		}
		$orderby = " ORDER BY monthNum DESC ";
		switch ($order) {
			case 'new' :
				$orderby = " ORDER BY shopId DESC ";
				break; // 默认按店铺ID
			case 'dist' :
				$orderby = " ORDER BY  juli ASC ";
				break; // 距离
			case 'qisongjia' :
				$orderby = " ORDER BY deliveryStartMoney ASC ";
				break; //
			case 'sales' :
				$orderby = " ORDER BY monthNum DESC ";
				break;
		}
		$sql = "select * from(SELECT shopId,longitude,latitude,shopStatus,shopAtive,goodsCatId1,shopName,shopImg,deliveryStartMoney,deliveryFreeMoney,deliveryMoney,deliveryCostTime,serviceStartTime,serviceEndTime,serviceStartTime2,serviceEndTime2,
		    ROUND(6378.138*2*ASIN(SQRT(POW(SIN(($latitude*PI()/180-latitude*PI()/180)/2),2)+COS($latitude*PI()/180)*COS(latitude*PI()/180)*POW(SIN(($longitude*PI()/180-longitude*PI()/180)/2),2)))*1000) AS juli
		    ,(SELECT count(orderId) FROM oto_orders WHERE isPay=1 and oto_orders.shopId=oto_shops.shopId) as monthNum,(select AVG(attitude) from oto_goods_sun where user_id=oto_shops.shopId) as avgPinFen  FROM oto_shops where shopStatus=1 and shopFlag=1  and (shopAtive=0
		        or (
		        CASE
				WHEN serviceStartTime <= serviceEndTime THEN
					(
						CASE
						WHEN serviceStartTime = 0
						AND serviceEndTime = 0 THEN
							TRUE
						WHEN serviceStartTime <= HOUR (now())
						AND HOUR (now()) < serviceEndTime THEN
							FALSE
						ELSE
							TRUE
						END
					)
				WHEN serviceStartTime > serviceEndTime THEN
					(
						CASE
						WHEN HOUR (now()) >= serviceStartTime
						OR HOUR (now()) < serviceEndTime THEN
							FALSE
						ELSE
							TRUE
						END
					)
					END
		        ) and
		        
		        (
		
					CASE
				WHEN serviceStartTime2 <= serviceEndTime2 THEN
					(
						CASE
						WHEN serviceStartTime2 = 0
						AND serviceEndTime2 = 0 THEN
							TRUE
						WHEN serviceStartTime2 <= HOUR (now())
						AND HOUR (now()) < serviceEndTime2 THEN
							FALSE
						ELSE
							TRUE
						END
					)
				WHEN serviceStartTime2 > serviceEndTime2 THEN
					(
						CASE
						WHEN HOUR (now()) >= serviceStartTime2
						OR HOUR (now()) < serviceEndTime2 THEN
							FALSE
						ELSE
							TRUE
						END
					)
					END
		        ) 
		        )
		    $where) as a where  a.shopStatus=1
		    $orderby limit 0,30";
//a. juli <10000  and
		// logResult($sql);
		$res = M ()->query ( $sql );
		$couponDB=M('coupon');
		$time=time();
		foreach ($res as $k=>$v){
	        $res[$k]['offLine']=1;
	        $res[$k]['serviceStartTime2']=intval($v['serviceStartTime2']);
	        $res[$k]['serviceEndTime2']=intval($v['serviceEndTime2']);
	        $res[$k]['coupon']=$couponDB->where(array('shopId'=>$v['shopId'],'isDel'=>1,'_string'=>"startTime<=$time and endTime>=$time"))->field('couponUp,couponReduce,isFirst')->order('couponUp ASC')->select();
	        //计算好评率
	        if(empty($v['avgPinFen'])){
	            $res[$k]['avgPinFen']=100;
	            $res[$k]['feng']=sprintf("%0.1f",5);;
	        }else{
	            $res[$k]['feng']=sprintf("%0.1f",$res[$k]['avgPinFen']);
	            $res[$k]['avgPinFen']=round(($v['avgPinFen']/5)*100);
	        }
	    }
		
		return $res;
		//echo json_encode( $res );
	}
	
	
	// 附近3公里的非营业中的订单
	public function shopOffLineList() {
	    // 店铺分类
	    $shopSort = I ( 'shopsort' ) ? I ( 'shopsort' ) : 0;
	    // 第几页
	    $page = I ( 'page' );
	    // 经度
	    $longitude = I ( 'longitude' );
	    // 纬度
	    $latitude = I ( 'latitude' );
	    // 排序
	    $order = I('order')?I('order'): 'sales';
	    if (! $longitude || ! $latitude || $latitude == 'undefined' || $longitude == 'undefined') {
	        // 获取位置失败
	        echo json_encode( array (
	            'status' => - 1
	        ) );
	        return;
	    }
	    $where = "";
	    if ($shopSort && $shopSort != 'undefined') {
	        $where = " and goodsCatId1= $shopSort ";
	    }
	    $orderby = " ORDER BY monthNum DESC ";
	    switch ($order) {
	        case 'new' :
	            $orderby = " ORDER BY shopId DESC ";
	            break; // 默认按店铺ID
	        case 'dist' :
	            $orderby = " ORDER BY  juli ASC ";
	            break; // 距离
	        case 'qisongjia' :
	            $orderby = " ORDER BY deliveryStartMoney ASC ";
	            break; //
	        case 'sales' :
	            $orderby = " ORDER BY monthNum DESC ";
	            break;
	    }
	    $limit = 30;
	    $start = $page * $limit;
	   	$sql = "select * from(SELECT shopId,longitude,latitude,shopStatus,shopAtive,goodsCatId1,shopName,shopImg,deliveryStartMoney,deliveryFreeMoney,deliveryMoney,deliveryCostTime,serviceStartTime,serviceEndTime,serviceStartTime2,serviceEndTime2,
		    ROUND(6378.138*2*ASIN(SQRT(POW(SIN(($latitude*PI()/180-latitude*PI()/180)/2),2)+COS($latitude*PI()/180)*COS(latitude*PI()/180)*POW(SIN(($longitude*PI()/180-longitude*PI()/180)/2),2)))*1000) AS juli
		    ,(SELECT count(orderId) FROM oto_orders WHERE isPay=1 and oto_orders.shopId=oto_shops.shopId) as monthNum,(select AVG(attitude) from oto_goods_sun where user_id=oto_shops.shopId) as avgPinFen  FROM oto_shops where shopStatus=1 and shopFlag=1  and (shopAtive=0
		        or (
		        CASE
				WHEN serviceStartTime <= serviceEndTime THEN
					(
						CASE
						WHEN serviceStartTime = 0
						AND serviceEndTime = 0 THEN
							TRUE
						WHEN serviceStartTime <= HOUR (now())
						AND HOUR (now()) < serviceEndTime THEN
							FALSE
						ELSE
							TRUE
						END
					)
				WHEN serviceStartTime > serviceEndTime THEN
					(
						CASE
						WHEN HOUR (now()) >= serviceStartTime
						OR HOUR (now()) < serviceEndTime THEN
							FALSE
						ELSE
							TRUE
						END
					)
					END
		        ) and
		        
		        (
		
					CASE
				WHEN serviceStartTime2 <= serviceEndTime2 THEN
					(
						CASE
						WHEN serviceStartTime2 = 0
						AND serviceEndTime2 = 0 THEN
							TRUE
						WHEN serviceStartTime2 <= HOUR (now())
						AND HOUR (now()) < serviceEndTime2 THEN
							FALSE
						ELSE
							TRUE
						END
					)
				WHEN serviceStartTime2 > serviceEndTime2 THEN
					(
						CASE
						WHEN HOUR (now()) >= serviceStartTime2
						OR HOUR (now()) < serviceEndTime2 THEN
							FALSE
						ELSE
							TRUE
						END
					)
					END
		        ) 
		        )
		    $where) as a where  a.shopStatus=1
		    $orderby limit 0,30";
		// where a. juli <10000
	    $res = M ()->query ( $sql );
	    
	    $couponDB=M('coupon');
		$time=time();
	    foreach ($res as $k=>$v){
	        $res[$k]['offLine']=1;
	        $res[$k]['serviceStartTime2']=intval($v['serviceStartTime2']);
	        $res[$k]['serviceEndTime2']=intval($v['serviceEndTime2']);
	        $res[$k]['coupon']=$couponDB->where(array('shopId'=>$v['shopId'],'isDel'=>1,'_string'=>"startTime<=$time and endTime>=$time"))->field('couponUp,couponReduce,isFirst')->order('couponUp ASC')->select();
	        //计算好评率
	        if(empty($v['avgPinFen'])){
	            $res[$k]['avgPinFen']=100;
	            $res[$k]['feng']=sprintf("%0.1f",5);;
	        }else{
	            $res[$k]['feng']=sprintf("%0.1f",$res[$k]['avgPinFen']);
	            $res[$k]['avgPinFen']=round(($v['avgPinFen']/5)*100);
	        }
	    }
	    
	    echo json_encode( $res );
	}
	
	
	// 搜索
	public function getSearchResult() {
	    // 第几页
	    $searchKey = I ( 'searchKey' );
	    $page = I ( 'page' ) ? I ( 'page' ) : 0;
	    // 经度
	    $longitude = I ( 'longitude' );
	    // 纬度
	    $latitude = I ( 'latitude' );
	    if (! $longitude || ! $latitude || $latitude == 'undefined' || $longitude == 'undefined') {
	        // 获取位置失败
	        echo json_encode( array (
	            'status' => - 1
	        ) );
	        return;
	    }
	    $where = "";
	    $limit = 30;
	    $start = $page * $limit;
	    $sql = <<<Eof
SELECT
	*
FROM
	(
		SELECT
			oto_shops.shopId,
			oto_shops.shopFlag,
            oto_shops.shopStatus,
            oto_shops.shopAtive,
			oto_shops.longitude,
			oto_shops.latitude,
			oto_shops.goodsCatId1,
			oto_shops.shopName,
			oto_shops.shopImg,
			oto_shops.deliveryStartMoney,
			oto_shops.deliveryFreeMoney,
			oto_shops.deliveryMoney,
			oto_shops.deliveryCostTime,
			oto_shops.serviceStartTime,
			oto_shops.serviceEndTime,oto_shops.serviceStartTime2,oto_shops.serviceEndTime2,
			ROUND(
				6378.138 * 2 * ASIN(
					SQRT(
						POW(
							SIN(
								(
									$latitude * PI() / 180 - oto_shops.latitude * PI() / 180
								) / 2
							),
							2
						) + COS($latitude * PI() / 180) * COS(
							oto_shops.latitude * PI() / 180
						) * POW(
							SIN(
								(
									$longitude * PI() / 180 - oto_shops.longitude * PI() / 180
								) / 2
							),
							2
						)
					)
				) * 1000
			) AS juli,
			(
				SELECT
					count(orderId)
				FROM
					oto_orders
				WHERE
					 isPay = 1
				AND oto_orders.shopId = oto_shops.shopId
			) AS monthNum,(select AVG(attitude) from oto_goods_sun where user_id=oto_shops.shopId) as avgPinFen 
		FROM
			oto_shops
		WHERE
			oto_shops.shopStatus = 1 
		AND oto_shops.shopName LIKE '%$searchKey%'
		OR EXISTS (
			SELECT
				1
			FROM
				oto_goods
			WHERE
				oto_goods.shopId = oto_shops.shopId
			AND oto_goods.goodsName LIKE '%$searchKey%'
		)
	) AS a
 WHERE  
shopFlag=1 and shopStatus=1  
ORDER BY
	juli ASC
LIMIT $start,$limit
Eof;

//and a.shopAtive=1  AND HOUR (curtime()) >= a.serviceStartTime AND HOUR (curtime()) <= a.serviceEndTime
//a.juli < 10000 and
	    // AND HOUR (curtime()) >= oto_shops.serviceStartTime
	    // AND HOUR (curtime()) <= oto_shops.serviceEndTime
	     $res = M ()->query ( $sql );
		 $H=intval(date('G'));
		 $couponDB=M('coupon');
		 $time=time();
	    if($res){
    	    foreach($res as $k=>$v){
				
				 $res[$k]['serviceStartTime2']=intval($v['serviceStartTime2']);
				 $res[$k]['serviceEndTime2']=intval($v['serviceEndTime2']);
				 $res[$k]['coupon']=$couponDB->where(array('shopId'=>$v['shopId'],'isDel'=>1,'_string'=>"startTime<=$time and endTime>=$time"))->field('couponUp,couponReduce,isFirst')->order('couponUp ASC')->select();
				 //计算好评率
				 if(empty($v['avgPinFen'])){
					 $res[$k]['avgPinFen']=100;
					 $res[$k]['feng']=sprintf("%0.1f",5);;
				 }else{
					 $res[$k]['feng']=sprintf("%0.1f",$res[$k]['avgPinFen']);
					 $res[$k]['avgPinFen']=round(($v['avgPinFen']/5)*100);
				 }
				
    	        $S1=$v['serviceStartTime'];
    	        $E1=$v['serviceEndTime'];
    	        $S2=$v['serviceStartTime2'];
    	        $E2=$v['serviceEndTime2'];
    	        $status=false;
				if($S1>$E1){
					if($H>=$S1){//当前时间大于开始时间
						$status=true;
					}else if($E1>$H) {//结束时间大于当前时间
						$status=true;
					}
				}else{
					//当前时间在开始和结束之间
						if($S1==0&&$E1==0){
							
						}else{
							if($H>=$S1&&$H<$E1){
								$status=true;
							}
						}
				}
				if(!$status){
					if($S2>$E2){
						if($H>=$S2){//当前时间大于开始时间
							$status=true;
						}else if($E2>$H) {//结束时间大于当前时间
							$status=true;
						}
					}else{
						//当前时间在开始和结束之间
						if($S2==0&&$E2==0){
							
						}else{
							if($H>=$S2&&$H<$E2){
								$status=true;
							}
						}
					}
				}
    	        //营业时间
    	        if($status){
    	            $res[$k]['service']=1;
    	            if ($res[$k] ['shopAtive'] == 0 ) {
    	                $res[$k] ['service'] = 0;
    	            } 
    	        }else{
    	            $res[$k]['service']=0;
    	        }
    	         
    	    }
	      }
	    echo json_encode( $res );
	}
	
	
	// 商家登录
	public function Blogin() {
		// 默认状态为
		$res ['status'] = - 1;
		$uname = I ( 'uname' );
		$upwd = I ( 'upwd' );
		$imei=I('imei');
		// file_put_contents("tsxx.txt", "\r\n--------1:".$_REQUEST['uname']."\r\n", FILE_APPEND);
		// file_put_contents("tsxx.txt", "\r\n--------1:".$POST['uname']."\r\n", FILE_APPEND);
		// file_put_contents("tsxx.txt", "\r\n--------1:".$GET['uname']."\r\n", FILE_APPEND);
		if (empty ( $uname ) || empty ( $upwd )) {
			print_r ( json_encode ( $res ) );
		}
		$map ['userPhone'] = $uname;
		$map ['userFlag'] = 1;
		$map ['userStatus'] = 1;
		$map ['userType'] = 1; // 类型为1是商家
		$isExists = M ( 'users' )->where ( $map )->find ();
		 // file_put_contents("tsxx.txt", "\r\n0:".json_encode($isExists)."\r\n", FILE_APPEND);
		 // file_put_contents("tsxx.txt", "\r\n0:".json_encode($map)."\r\n", FILE_APPEND);
		if ($isExists) { // 店主登录
			if ($isExists ['loginPwd'] == md5 ( $upwd . $isExists ['loginSecret'] )) {
				// 更新一下用户最后一次登录的信息
				$data = array ();
				$data ['lastTime'] = date ( 'Y-m-d H:i:s' );
				$data ['lastIP'] = get_client_ip ();
				if($imei){
				    $data ['bizImei'] =$imei;
				}
				$m = M ( 'users' );
				$m->where (array ('userId' => $isExists ['userId'] ) )->data ( $data )->save ();
				
				// 返回数据
				$isExists ['status'] = 1; // 店主登录成功
				

				$shopInfo = M ( 'shops' )->where ( array (
						'userId' => $isExists ['userId'] 
				) )->field ( 'shopName,shopAddress,shopId,kefuLink,shopImg' )->find ();
				//file_put_contents("tsxx.txt", "\r\n".$isExists ['userId']."\r\n", FILE_APPEND);
				$isExists ['shopName'] = $shopInfo ['shopName'];
				$isExists ['userName'] = $isExists ['userName'];
				$isExists ['shopId'] = $shopInfo ['shopId'];
				$isExists ['kefuLink'] = $shopInfo ['kefuLink'];
				$isExists ['shopAddress'] = $shopInfo ['shopAddress'];
				$isExists ['shopImg'] = $shopInfo ['shopImg'];
				print_r ( json_encode ( $isExists ) );
				 //file_put_contents("tsxx.txt", "\r\n1:".json_encode($isExists)."\r\n", FILE_APPEND);
			} else {
				print_r ( json_encode ( $res ) );
				// file_put_contents("tsxx.txt", "\r\n2:".json_encode($res)."\r\n", FILE_APPEND);
			}
		} else {
			// 店员登录
			$staff = M ( 'staff' )->where ( array (
					'telephone' => $uname,'roleId'=>1 
			) )->find ();
			if ($staff) {
				$shopkeeper = M ( 'users' )->where ( array (
						'userId' => $staff ['userId'],
						'userFlag' => 1 
				) )->getField ( 'loginSecret' );
				if ($staff ['password'] == md5 ( $upwd . $shopkeeper )) {
					$staff ['status'] = 2; // 店员登录成功
					$data ['logtime'] = time ();
					if($imei){
					    $data ['imeis'] =$imei;
					}
					M ( 'staff' )->where ( array (
							'id' => $staff ['id'] 
					) )->save ( $data );
					$shopInfo = M ( 'shops' )->where ( array (
							'u.userId' => $staff ['userId'] 
					) )->join ( 'as s left join oto_users as u on u.userId=s.userId' )->field ( 's.shopName,s.shopAddress,s.shopId,u.userName,s.shopImg' )->find ();
					$staff ['shopName'] = $shopInfo ['shopName'];
					$staff ['shopId'] = $shopInfo ['shopId'];
					$staff ['userName'] = $shopInfo ['userName'];
					$staff ['shopAddress'] = $shopInfo ['shopAddress'];
					$staff ['shopImg'] = $shopInfo ['shopImg'];
					print_r ( json_encode ( $staff ) );
					// file_put_contents("tsxx.txt", "\r\n3:".json_encode($staff)."\r\n", FILE_APPEND);
				} else {
					print_r ( json_encode ( $res ) );
					// file_put_contents("tsxx.txt", "\r\n4:".json_encode($res)."\r\n", FILE_APPEND);
				}
			} else {
				$res ['status'] = - 2;
				print_r ( json_encode ( $res ) );
				// file_put_contents("tsxx.txt", "\r\n5:".json_encode($res)."\r\n", FILE_APPEND);
			}
		}
	}
	// 店主获取 没处理的订单
	public function getNoHandleOrder() {
		$shopId = I ( 'shopId' );
		$page = I ( 'page' ) ? I ( 'page' ) : 0;
		$limit = 30;
		$start = $page * $limit;
		$sql = "select orderId,orderNo,shopId,orderStatus,isRefund,payType,isSelf,isPay,needPay,totalMoney,userPhone,userName,userAddress,createTime  from oto_orders as a where shopId=$shopId  and orderStatus=0 and isPay=1 order by orderId desc limit  $start,$limit  ";
		$res = M ()->query ( $sql );
		if ($res) {
			// 每个订单下面的商品
			foreach ( $res as $k => $v ) {
				$res [$k] ['goodsList'] = M ( 'order_goods' )->where ( array (
						'orderId' => $v ['orderId'] 
				) )->select ();
			}
		}
		echo json_encode( $res );
	}
	// 获取总共有多少订单需要处理
	public function getNoHandleOrderNum() {
		$shopId = I ( 'shopId' );
		$res = M ( 'orders' )->where ( array (
				'shopId' => $shopId,
				'isPay' => 1,
				'orderStatus' => 0 
		) )->count ();
		echo $res;
	}
	// 获取订单详情
	public function getOrderDetail() {
		$shopId = I ( 'shopId' );
		$orderId = I ( 'orderId' );
		$sql = "select s.shopTel,s.shopName as sname,t.telephone,t.username as staffName,o.isRefund,o.deliverMoney,o.orderId,o.staffId,o.orderNo,o.shopId,o.orderStatus,o.payType,o.isSelf,o.isPay,o.totalMoney,o.needPay,o.userPhone,o.userName,o.userAddress,o.createTime,o.orderRemarks,o.requireTime,FROM_UNIXTIME(o.payTime) as payTime,o.pickup,o.requireTime,o.orderRemarks from oto_orders as o left join oto_staff as t on t.id=o.staffId left join oto_shops as s on s.shopId=o.shopId  where o.shopId=$shopId and o.orderId=$orderId";
		//file_put_contents("tsxx.txt", "\r\n".$sql."\r\n", FILE_APPEND);
		$res = M ()->query ( $sql );
		if ($res) {
			// 每个订单下面的商品
			foreach ( $res as $k => $v ) {
				$res [$k] ['goodsList'] = M ( 'order_goods' )->where ( array (
						'orderId' => $v ['orderId'] 
				) )->select ();
			}
		}
		echo json_encode( $res );
	}
	// 获取店铺的配送员
	public function getStaff() {
		$shopid = I ( 'shopId' );//下个版本直接传userid过来即可
		$userid=M('shops')->where(array('shopId'=>$shopid))->getField('userId');
		$field = "id,telephone,username";
		$res = M ( 'staff' )->where ( array ('userId' => $userid,'roleId'=>1) )->field ( $field )->select ();
		echo json_encode( $res );
	}
	// 为订单指定配送员
	public function selectDelivery() {
		$shopid = I ( 'shopId' );
		$orderid = I ( 'orderId' );
		$userid = I ( 'userid' );
		$res = M ( 'orders' )->where ( array (
				'orderId' => $orderid,
				'shopId' => $shopid 
		) )->setField ( array (
				'staffId' => $userid 
		) );
		if ($res != false) {
			echo json_encode( array (
					'status' => 0 
			) );
		} else {
			echo json_encode( array (
					'status' => - 1 
			) );
		}
	}
	// 下一订单，店主订单详情页面
	public function nextOrder() {
		$shopId = I ( 'shopId' );
		$orderId = I ( 'orderId' );
		$sql = "select oto_staff.username as staffName,orderId,staffId,telephone,orderNo,shopId,deliverMoney,orderStatus,payType,isSelf,isPay,totalMoney,needPay,userPhone,oto_orders.userName,userAddress,createTime,requireTime,orderRemarks  from oto_orders left join oto_staff on oto_staff.id=oto_orders.staffId  where shopId=$shopId and orderStatus=0 and isPay=1 and orderId<$orderId   order by orderId desc limit 1";
		$res = M ()->query ( $sql );
		if (! $res) {
			$sql = "select oto_staff.username as staffName,orderId,staffId,telephone,orderNo,shopId,deliverMoney,orderStatus,payType,isSelf,isPay,totalMoney,needPay,userPhone,oto_orders.userName,userAddress,createTime,requireTime,orderRemarks  from oto_orders left join oto_staff on oto_staff.id=oto_orders.staffId  where shopId=$shopId  and orderStatus=0 and isPay=1  order by orderId desc limit 1";
			$res = M ()->query ( $sql );
		}
		if ($res) {
			// 每个订单下面的商品
			foreach ( $res as $k => $v ) {
				$res [$k] ['goodsList'] = M ( 'order_goods' )->where ( array (
						'orderId' => $v ['orderId'] 
				) )->select ();
			}
		}
		echo json_encode( $res );
	}
	// 获取处理中的订单
	public function getNoHandleOrderIng() {
		$shopId = I ( 'shopId' );
		$page = I ( 'page' ) ? I ( 'page' ) : 0;
		$limit = 30;
		$start = $page * $limit;
		$sql = "select o.orderId,o.orderNo,o.shopId,o.orderStatus,o.isRefund,o.payType,o.isSelf,o.isPay,o.totalMoney,o.needPay,o.userPhone,o.userName,o.userAddress,o.createTime,r.biz_status as rstatus,r.pf_status  from oto_orders as o left join oto_refund as r on r.orderid=o.orderId where o.shopId=$shopId and (o.orderStatus in(1,2,3,-3,-4,-5,-6,-7)) and (isRefund in(0,1,3)) and isPay=1 order by orderId desc limit $start,$limit  ";
		$res = M ()->query ( $sql );
		if ($res) {
			// 每个订单下面的商品
			foreach ( $res as $k => $v ) {
				$res [$k] ['goodsList'] = M ( 'order_goods' )->where ( array (
						'orderId' => $v ['orderId'] 
				) )->select ();
			}
		}
		echo json_encode( $res );
	}
	// 获取已完成的订单(isRefund=2包括已经退款订单)
	public function getNoHandleOrderComplete() {
		$shopId = I ( 'shopId' );
		$page = I ( 'page' ) ? I ( 'page' ) : 0;
		$limit = 30;
		$start = $page * $limit;
		$sql = "select orderId,orderNo,isRefund,shopId,orderStatus,payType,isSelf,isPay,needPay,totalMoney,userPhone,userName,userAddress,createTime  from oto_orders as a where shopId=$shopId and (orderStatus in(4,-4) or isRefund=2)   and isPay=1 order by orderId desc limit  $start,$limit  ";
		$res = M ()->query ( $sql );
		if ($res) {
			// 每个订单下面的商品
			foreach ( $res as $k => $v ) {
				$res [$k] ['goodsList'] = M ( 'order_goods' )->where ( array (
						'orderId' => $v ['orderId'] 
				) )->select ();
			}
		}
		echo json_encode($res);
		//echo json_encode( $res );
	}
	// 处理订单，改变订单状态
	public function handleOrder() {
		// orderStatus 0未处理 1确认，2打印，3配送中，4已经收货
		$shopId = I ( 'shopId' );
		$status = I ( 'status' );
		$orderid = I ( 'orderid' );
		$statusVal = '';
		$info = M ( 'orders' )->where ( array (
				'shopId' => $shopId,
				'orderId' => $orderid
		) )->field ( 'orderNo,totalMoney,shopId,needPay,userId,orderScore,isPrint,isRefund,orderStatus,staffId' )->find ();
		file_put_contents("tsxx.txt", "-----------\r\n3340:".json_encode($info)."\r\n", FILE_APPEND);
		 //是否限制打印后才能处理订单
		/*  if($status!=-2){
			if($info['isPrint']==0){
				echo json_encode( array (
				'status' => -2
				) );
				return;
			}
		}  */
		//商户不接单，客户取消订单
		if($info['orderStatus']==-3){
			echo json_encode( array (
			'status' => -5
			) );
			return;
		}
		//商户不接单，客户取消订单
		if($info['orderStatus']==-4){
			echo json_encode( array (
			'status' => -6
			) );
			return;
		}
		if($info['isRefund']==1){//退款中0为正常，1退款中，2同意退款，3为拒绝退款，拒绝退款则正常配送
			//if($info['isRefundHandle']==0){
				echo json_encode( array (
				'status' => -3 //退款中
				) );
				return;
			//}
		}else if($info['isRefund']==2){
			echo json_encode( array (
			'status' => -4 //同意退款
			) );
			return;
		}else if($info['isRefundHandle']==1){
				echo json_encode( array (
				'status' => -7 //退款中
				) );
				return;
			}
		M ()->startTrans ();
		$res = M ( 'orders' )->where ( array (
				'shopId' => $shopId,
				'orderId' => $orderid 
		)
		 )->setField ( array (
				'orderStatus' => $status 
		) );
		file_put_contents("tsxx.txt", "\r\n3390:".json_encode($res)."\r\n", FILE_APPEND);
		if ($res != false) {
			if($status==3){
			    if($info['orderStatus']>=3){
			        echo json_encode( array ( 'status' => -1 ) );
			        M()->rollback();
			        return;
			    }
				//配送
				$c = M ( 'orders' )->where ( array (
						'orderId' => $orderid
				) )->setField ( array (
						'receiving' => time ()
				) ); // 更新订单状态
				file_put_contents("tsxx.txt", "\r\n3404:".json_encode($c)."\r\n", FILE_APPEND);
				if($c!==false){
					M()->commit();
					echo json_encode( array (
					'status' => 0
					) );
				}else{
					echo json_encode( array (
					'status' => -1
					) );
					M()->rollback();
				}
			}else if ($status == - 2) {//订单无效
				file_put_contents("tsxx.txt", "\r\n3417:订单无效"."\r\n", FILE_APPEND);
			  if($info['orderStatus']>0){
			  		file_put_contents("tsxx.txt", "\r\n3419:orderStatus>0"."\r\n", FILE_APPEND);
			        echo json_encode( array ( 'status' => -1 ) );
			        M()->rollback();
			        return;
			    }
				 $b = M ( 'users' )->where ( array ( // 还原金额
						'userId' => $info ['userId'] 
				) )->setInc ( 'userMoney', $info ['needPay'] );
				file_put_contents("tsxx.txt", "\r\n3427:".json_encode($b)."\r\n", FILE_APPEND);
				$balance = M ( 'users' )->where ( array (
						'userId' => $info ['userId'] 
				) )->field ( 'userMoney,userScore' )->find ();
				file_put_contents("tsxx.txt", "\r\n3431:".json_encode($balance)."\r\n", FILE_APPEND);
				// 记录积分变动和余额变动
				$this->OperationMoneyRecord ( 5, $info ['needPay'], $info['orderNo'], 1, $info ['userId'], $balance ['userMoney'],'',0 );
				$this->OperationScoreRecord ( 4, $info ['shopId'], $info ['needPay'], $orderid, 0, $info ['userId']);
				file_put_contents("tsxx.txt", "\r\n3433:".json_encode($b)."\r\n", FILE_APPEND);
				if($b!==false){
					M()->commit();
					echo json_encode( array (
					'status' => 0
					) );
				}else{
					M()->rollback();
				} 
			} else if ($status == 4) {//订单已完成
			    if($info['orderStatus']>=4){
			        echo json_encode( array ( 'status' => -1 ) );
			        M()->rollback();
			        return;
			    }
				// 更新商家余额
				$f = M ( 'shops' )->where ( array (
						'shopId' => $shopId 
				) )->setInc ( 'money', $info ['needPay'] );
				M('orders')->where(array('orderId'=>$orderid))->setField('signTime',time());
				file_put_contents("tsxx.txt", "\r\n3453:".json_encode($f)."\r\n", FILE_APPEND);
				if ($f !== false) {
					M ()->commit ();
					echo json_encode( array (
							'status' => 0 
					) );
				} else {
					M ()->rollback ();
					echo json_encode( array (
							'status' => - 1 
					) );
				}
			} else if($status==1){
			if($info['orderStatus']>=1){
			        echo json_encode( array ( 'status' => -1 ) );
			        M()->rollback();
			        return;
			    }
				//商家确认订单
				M ( 'orders' )->where ( array (
				'shopId' => $shopId,
				'orderId' => $orderid
				)
				)->setField ( array (
				'receiving' => time()
				) );
				M ()->commit ();
				echo json_encode( array (
				'status' => 0
				) );
				//如果有选择配送员，极光通知
				if($info['staff_Id']>0){
					$staffPhone=M('staff')->where(array('id'=>$info['staff_Id']))->getField('telephone');
					$this->pushtouser($staffPhone);
					try {
					    $this->sendMessToBiz($staffPhone,$info['orderNo']);
					    $this->sendMessToBiz('15115431966',$info['orderNo']);
					    $this->sendMessToBiz('13469135911',$out_trade_no);
					} catch (Exception $e) {
					}
					
				}
				return;
			} else {
				M ()->rollback ();
				echo json_encode( array (	'status' => - 1) );return;
			}
		}else{
			M ()->rollback ();
			echo json_encode( array (	'status' => - 1) );return;
		}
	}
	// 店员更改订单状态
	public function handleOrderStatus() {
		$shopId = I ( 'shopId' );
		$status = I ( 'status' );
		$orderid = I ( 'orderid' );
		$info = M ( 'orders' )->where ( array (
				'shopId' => $shopId,
				'orderId' => $orderid 
		) )->field ( 'orderStatus,isRefund,pickup' )->find ();
		if ($info ['pickup'] == 0) {
			// 还没收件
			echo json_encode( array (
					'status' => - 1 
			) );
			return;
		}
		if($info['isRefund']==1){//退款中0为正常，1退款中，2同意退款，3为拒绝退款，拒绝退款则正常配送
			echo json_encode( array (
			'status' => -2 //退款中
			) );
			return;
		}else if($info['isRefund']==2){
			echo json_encode( array (
			'status' => -3 //同意退款
			) );
			return;
		}

		$res = M ( 'orders' )->where ( array (
				'shopId' => $shopId,
				'orderId' => $orderid 
		) )->setField ( 'orderStatus', $status );
		if ($res != false) {
		   if($status==4){
		       $res = M ( 'orders' )->where ( array (
		           'shopId' => $shopId,
		           'orderId' => $orderid
		       ) )->setField ( 'signTime', time() );
		   }
			echo json_encode( array (
					'status' => 0 
			) );
			return;
		} else {
			echo json_encode( array (
					'status' => 1 
			) );
			return;
		}
	}
	// 状态提示
	public function getOrderStatusValByStatusId($status) {
		$statusVal = '';
		switch ($status) {
			case '-2' :
				$statusVal = '订单最新状态为无效';
				break;
			case '1' :
				$statusVal = '订单最新状态为确认';
				break;
			case '2' :
				$statusVal = '订单最新状态为打印';
				break;
			case '3' :
				$statusVal = '订单最新状态为配送中';
				break;
			case '4' :
				$statusVal = '订单最新状态为已完成';
				break;
		}
		return $statusVal;
	}
	// 店铺余额和店员列表
	public function getShopInfoStaff() {
		$shopid = I ( 'shopid' );
		$sql = "select b.userId, a.userName,b.bizMoney,b.shopName from oto_users as a left JOIN oto_shops as b on a.userId=b.userId where b.shopId=$shopid";
		$res = M ()->query ( $sql );
		$res [0] ['staff'] = M ( 'staff' )->where ( array (
				'userId' => $res[0]['userId'] ,'staffStatus'=>1//角色为1的为默认配送员
		) )->select ();
		echo json_encode( $res );
	}
	// 商家提现
	public function Withdraw() {

		$shopid = I ( 'shopid' );
		$shopInfo = M ( 'shops' )->where ( array (
				'shopId' => $shopid 
		) )->field ( 'bizMoney,userId,bankNo,bankId' )->find ();
		if(!$shopInfo['bankNo']||!$shopInfo['bankId']){
			echo json_encode(array('status'=>-1));
			return;
		}
		if ($shopInfo ['bizMoney'] > 0) {
		    //提现次数限制2次
		   $starTime=strtotime(date('Y-m-d'.'00:00:00'));
	       $endTime=strtotime(date('Y-m-d'.'23:59:59'));
	       $sql="select * from oto_withdraw where shopId=".$shopid." and createTime>=".$starTime." and createTime<=".$endTime." ";
	       //file_put_contents("tsxx.txt", "\r\n".$sql."\r\n", FILE_APPEND);
	       $times=M ()->query ( $sql );
	       $times=count($times);
	       //file_put_contents("tsxx.txt", "\r\n".$times."次\r\n", FILE_APPEND);
	       //$times=M('withdraw')->where(array('shopId'=>$shopid))->count();
	       // if($times>1){
	       //     echo json_encode( array (
	       //         'status' => 2
	       //     ) );
	       //     return;
	       // }
			M ()->startTrans ();
			$data ['userId'] = $shopInfo ['userId'];
			$data ['shopId'] = $shopid;
			$data ['cardName'] = $shopInfo ['userId'];//
			$data ['bankId'] = $shopInfo ['bankId'];
			$data ['bankNo'] = $shopInfo ['bankNo'];
			$data ['bankAddress'] = $shopInfo ['userId'];//
			$data ['createTime'] = time ();
			//$data ['ip'] = get_client_ip ();
			$data ['money'] = $shopInfo ['bizMoney'];
			$data['txNo'] = date('YmdHis',time()).rand(10000,99999);
			$res = M ( 'withdraw' )->data ( $data )->add ();
			if ($res) {
				$set = M ( 'shops' )->where ( array (
						'shopId' => $shopid 
				) )->setDec ( 'bizMoney', $shopInfo ['bizMoney'] );
				$set_order['withdrawId']=$res;
				$ser_pan=M('orders')->where(array('shopId'=>$shopid,'orderStatus'=>'4'))->data($set_order)->save();
				if ($set != false) {
					M ()->commit ();
					echo json_encode( array (
							'status' => 0 
					) );
				} else {
					M ()->rollback ();
					echo json_encode( array (
							'status' => - 1 
					) );
				}
			} else {
				M ()->rollback ();
				echo json_encode( array (
						'status' => - 1 
				) );
			}
		}else{
			echo json_encode( array (
			'status' => - 1
			) );
		}
	}
	// 配送员登录，显示配送员没处理的订单
	public function getNoHandleStaffOrder() {
		$userid = I ( 'userid' );
		$page = I ( 'page' ) ? I ( 'page' ) : 0;
		$limit = 30;
		$start = $page * $limit;
		$sql = "select orderId,orderNo,staffId,pickup,shopId,orderStatus,payType,isSelf,isPay,isRefund,needPay,totalMoney,userPhone,userName,userAddress,createTime  from oto_orders as a where staffId=$userid  and orderStatus between 1 and 3 and isPay=1 and isRefund not in(1,2) order by orderId desc limit  $start,$limit  ";
		$res = M ()->query ( $sql );
		if ($res) {
			// 每个订单下面的商品
			foreach ( $res as $k => $v ) {
				$res [$k] ['goodsList'] = M ( 'order_goods' )->where ( array (
						'orderId' => $v ['orderId'] 
				) )->select ();
			}
		}
		echo json_encode( $res );
	}
	// 获取有多少订单没处理
	public function getNoHandleStaffOrderNum() {
		$userid = I ( 'userid' );
		$shopid = I ( 'shopid' );
		$res = M ( 'orders' )->where ( array (
				'shopId' => $shopid,
				'staffId' => $userid,
				'isPay' => 1,
				'isRefund'=>array('not in','1,2'),
				'orderStatus' => array (
						'between',
						'1,3'
				) 
		) )->count ();
		echo $res;
	}
	// 配送员取件
	public function handleOrderPickUp() {
		$userid = I ( 'userid' );
		$orderid = I ( 'orderid' );
		$isrefund=M('orders')->where(array('orderId'=>$orderid))->getField('isRefund');
		if($isrefund==1){
			echo json_encode( array (
			'status' => - 2
			) );
			return;
		}
		if($isrefund==2){
			echo json_encode( array (
			'status' => - 3
			) );
			return;
		}
		$res = M ( 'orders' )->where ( array (
				'orderId' => $orderid,
				'staffId' => $userid 
		) )->setField ( 'pickup', 1 );
		if ($res != FALSE) {
			echo json_encode( array (
					'status' => 0 
			) );
		} else {
			echo json_encode( array (
					'status' => - 1 
			) );
		}
	}
	
	// 下一订单，配送员订单详情页面
	public function nextStaffOrder() {
		$userid = I ( 'userid' );
		$orderId = I ( 'orderId' );
		$sql = "select pickup,orderId,staffId,deliverMoney,isRefund,orderNo,shopId,orderStatus,payType,isSelf,isPay,needPay,totalMoney,userPhone,userName,userAddress,createTime,signTime,requireTime,orderRemarks  from oto_orders where staffId=$userid   and orderStatus!=4 and isPay=1 and isRefund not in(1,2)  and orderId<$orderId order by orderId desc limit 1";
		$res = M ()->query ( $sql );
		if (! $res) {
			$sql = "select orderId,staffId,deliverMoney,isRefund,orderNo,shopId,orderStatus,payType,isSelf,isPay,needPay,totalMoney,userPhone,userName,userAddress,createTime,signTime,requireTime,orderRemarks  from oto_orders where staffId=$userid   and orderStatus!=4  and isRefund not in(1,2)  and  isPay=1  order by orderId desc limit 1";
			$res = M ()->query ( $sql );
		}
		if ($res) {
			// 每个订单下面的商品
			foreach ( $res as $k => $v ) {
				$res [$k] ['goodsList'] = M ( 'order_goods' )->where ( array (
						'orderId' => $v ['orderId'] 
				) )->select ();
			}
		}
		echo json_encode( $res );
	}
	
	// 获取配送员已完成的订单
	public function getStaffOrderComplete() {
		$shopId = I ( 'shopId' );
		$userid = I ( 'userid' );
		$page = I ( 'page' ) ? I ( 'page' ) : 0;
		$limit =30;
		$start = $page * $limit;
		$sql = "select orderId,orderNo,isRefund,shopId,orderStatus,payType,isSelf,isPay,needPay,totalMoney,userPhone,userName,userAddress,createTime,signTime  from oto_orders as a where shopId=$shopId and staffId=$userid and (orderStatus=4 or isRefund!=0)  and isPay=1 order by orderId desc limit  $start,$limit  ";
		$res = M ()->query ( $sql );
		if ($res) {
			// 每个订单下面的商品
			foreach ( $res as $k => $v ) {
				$res [$k] ['goodsList'] = M ( 'order_goods' )->where ( array (
						'orderId' => $v ['orderId'] 
				) )->select ();
			}
		}
		echo json_encode( $res );
	}
	// 客户主动取消订单
	public function canCelOrder() {
		$orderid = I ( 'orderNo' );
		$info = M ( 'orders' )->where ( array (
				'orderId' => $orderid 
		) )->find();
		$isTrue=$info['orderStatus'];
		if ($isTrue > 0||$isTrue<=-2) {
			//状态已改变
			echo json_encode( array (
					'status' => - 3 
			) );
			return;
		}
		M ()->startTrans ();
			$data['orderid']=$orderid;
			$this->checkStock($orderid,0,1);
			$data['time']=time();
			$data['money']=$info['needPay'];
			$data['userid']=$info['userId'];
			$data['shopid']=$info['shopId'];
			$data['reason']='';
			$data['status']='0';
			$data['type']=1;//取消订单
			$A=M('refund')->data($data)->add();
			if($A){////取消订单中
			    $B = M ( 'orders' )->where ( array ( 'orderId' => $orderid,'isPay' => 1  ) )->setField ( array ( 'orderStatus' => - 3  ) );
			    $C= $this->handleRefund($A,$info['needPay']);
			    if($A&&$B&&$C){
			        M()->commit();
			        echo json_encode( array (	'status' => 0) );
			    }else{
			        M()->rollback();
			        echo json_encode( array ('status' => -1) );
			    }
			}else{
			    M()->rollback();
				echo json_encode( array ('status' => -1) );
			}
	}
	
	public function handleRefund($id,$money){
	        $refundInfo = M ( 'refund' )->where ( array ( 'id' => $id ) )->find ();
	        $a = M ( 'refund' )->where ( array ('id' => $id ) )->setField ( array (
	            'pfstatus' => 1,
	            'rmoney' => $money,
	            'pftime' => time (),
	            'rway' => 0//退到余额
	        ) );
	        // 更新退款状态
	        $b = M ( 'orders' )->where ( array ( 'orderId' => $refundInfo ['orderid'] ) )->setField ( array ( 'orderStatus' => '-4' ) );
	        $oInfo = M ( 'orders' )->where ( array ('orderId' => $refundInfo ['orderid'] ) )->field('needPay,shopId')->find();
	        $field = "o.orderNo,o.shopId,o.userId,o.needPay,u.userMoney,u.userScore";
	        $info = M ( 'orders' )->field ( $field )->where ( array (
	            'orderId' => $refundInfo ['orderid']
	        ) )->join ( 'as o left join oto_users as u on o.userId=u.userId' )->find ();
	        // 添加余额变动记录
	        // 退还余额时进行余额变动记录操作
	        $this->OperationMoneyRecord ( 2, $money, $info ['orderNo'], 1, $info ['userId'], $info ['userMoney'] + $money,'',0 );
	        $score=$info['userScore']-intval($money);
	        $this->OperationScoreRecord ( 2, $oInfo ['shopId'], $money, $info ['orderNo'], 0, $info ['userId'] );
	        $m=M('users')->where(array('userId'=>$info ['userId']))->setInc('userMoney',$money);
	        if ($a != false&&$b!=false) {
	            	  return 1;
	        } else {
	                  return 0;
	        }
	}
	
	
	// 金额操作记录
	/**
	 * 构造函数
	 * @param $type 操作类型,1下单，2取消订单，3充值，4提现,5订单无效, 6贷款成功，7还款，8减少金额，9信用还款
	 * @param $money 金额        	
	 * @param $orderid 订单ID或者充值ID        	
	 * @param $IncDec 余额变动 0为减，1加
	 * @param $userid 用户ID        	
	 * @param $balance 余额        	
	 * @param $remark 其它备注信息       	
	 */
	public function OperationMoneyRecord($type = '', $money = 0, $orderid = '', $IncDec = '', $userid = 0, $balance = 0,$remark='',$payWay=0) {
		$db = M ( 'money_record' );
		$data ['type'] = $type;
		$data ['money'] = $money;
		$data ['time'] = time ();
		$data ['ip'] = get_client_ip ();
		$data ['orderNo'] = $orderid;
		$data ['IncDec'] = $IncDec;
		$data ['userid'] = $userid;
		$data ['balance'] = $balance;
		$data ['remark'] = $remark;
		$data ['payWay'] = $payWay;
		//file_put_contents("tsxx.txt", "\r\n3854:".json_encode($data)."\r\n", FILE_APPEND);
		$res = $db->add ( $data );
		//file_put_contents("tsxx.txt", "\r\n3856:".$res."\r\n", FILE_APPEND);
		return $res;
	}
	
	// 积分操作记录
	/**
	 * 构造函数
	 *
	 * @param $type 1购物，2取消订单，3充值，4订单无效，5活动,6评价订单
	 *        	，6评价订单+1分
	 * @param $score 积分        	
	 * @param $shopid 店铺ID        	
	 * @param $orderid 订单ID或者充值ID        	
	 * @param $IncDec 积分变动
	 *        	0为减，1加
	 * @param $userid 用户ID        	
	 * @param $totalscore 用户剩余总积分        	
	 */
	public function OperationScoreRecord($type = '', $shopid, $payMoney=0, $orderid = '', $IncDec = '', $userid = 0) {
		$score=floor($payMoney);
		if($score<=0){
			return;
		}
		$fen=0;
		$userinfo=M('users')->where(array('userId'=>$userid))->find();
		// $scoreSetting=M('score_setting')->find();//查询积分配置
		// if($type==1){
		// 	if($scoreSetting['xiaofei']==-1){
		// 		$fen = $score;
		// 	}else{
		// 		$fen = $scoreSetting['xiaofei'];
		// 	}
		// }elseif($type==4){
		// 	if($scoreSetting['xiaofei']==-1){
		// 		$fen = $score;
		// 	}else{
		// 		$fen = $scoreSetting['xiaofei'];
		// 	}
		// }elseif ($type==3){
		// 	if($scoreSetting['chongzi']==-1){
		// 		$fen = $score;
		// 	}else{
		// 		$fen = $scoreSetting['chongzi'];
		// 	}
		// }elseif ($type==6){
		// 	if($scoreSetting['pingjia']==-1){
		// 		$fen = $score;
		// 	}else{
		// 		$fen = $scoreSetting['pingjia'];
		// 	}
		// }else if($type==2){
		//     if($scoreSetting['xiaofei']==-1){
		//         $fen = $score;
		//     }else{
		//         $fen = $scoreSetting['xiaofei'];
		//     }
		// }
		if($IncDec==0){
			$totalscore=$userinfo['userScore']-$fen;
			M ( 'users' )->where ( array (
			'userId' => $userid
			) )->setDec ( 'userScore', $fen ); // 更新积分
			M ( 'users' )->where ( array (
			'userId' => $userid
			) )->setDec ( 'userTotalScore', $fen); // 更新总积分
		}else{
			$totalscore=$userinfo['userScore']+$fen;
			M ( 'users' )->where ( array (
			'userId' => $userid
			) )->setInc ( 'userScore', $fen ); // 更新积分
			M ( 'users' )->where ( array (
			'userId' => $userid
			) )->setInc ( 'userTotalScore', $fen); // 更新总积分
		}
		$db = M ( 'score_record' );
		$data ['score'] = $fen;
		$data ['type'] = $type;
		$data ['time'] = time ();
		$data ['ip'] = get_client_ip ();
		$data ['orderNo'] = $orderid;
		$data ['IncDec'] = $IncDec;
		$data ['userid'] = $userid;
		$data ['totalscore'] = $totalscore;
		$res = $db->add ( $data );
		return $res;
	}
	
	// 获取用户最新信息比如积分金额等，不缓存
	public function getUsernewest() {
		$userid = I ( 'userid' );
		$field = "userScore,userTotalScore,userMoney";
		$uInfo = M ( 'users' )->where ( array (
				'userId' => $userid 
		) )->find ();
		echo json_encode( $uInfo );
	}
	
	// 最近30天的消费详情
	public function getUserMoneyDetail() {
		$userid = I ( 'userid' );
		$map ['userid'] = $userid;
		$map ['_string'] = ' DATE_SUB(CURDATE(), INTERVAL 30 DAY)<=FROM_UNIXTIME(time)';
		$res = M ( 'money_record' )->where ( $map )->order ( 'id desc' )->select ();
		echo json_encode( $res );
	}
	
	// 最近30天积分变动情况
	public function getUserScoreDetail() {
		$userid = I ( 'userid' );
		$map ['userid'] = $userid;
		$map ['_string'] = ' DATE_SUB(CURDATE(), INTERVAL 30 DAY)<=FROM_UNIXTIME(time)';
		$res = M ( 'score_record' )->where ( $map )->order ( 'id desc' )->select ();
		echo json_encode( $res );
	}
	
	// 判断是否已经有密码或者支付密码
	public function isExistsPwd() {
		$userid = I ( 'userid' );
		$res = M ( 'users' )->where ( array (
				'userId' => $userid 
		) )->field ( 'loginPwd,payPwd' )->find ();
		$login = $res ['loginPwd'] ? 1 : 0;
		$pay = $res ['payPwd'] ? 1 : 0;
		echo json_encode( array (
				'loginPwd' => $login,
				'payPwd' => $pay 
		) );
	}
	// 是否已经贷款过
	public function isExistsLoan() {
		$userid = I ( 'userid' );
		$res = M ( 'disposable' )->where ( array (
				'userid' => $userid 
		) )->find ();
		if ($res) {
			echo json_encode( array (
					'status' => 1 
			) );
		} else {
			echo json_encode( array (
					'status' => 0 
			) ); // 没借过
		}
	}
	
	// 申请贷款
	public function applyLoan() {
		// 贷款
		$data ['userid'] = I ( 'userid' );
		$data ['type'] = 1;
		$data ['purpose'] = I ( 'yongtu' );
		$data ['stime'] = time ();
		$isLoan = M ( 'disposable' )->where ( array (
				'userid' => $data ['userid'] 
		) )->find ();
		if ($isLoan) {
			echo json_encode( array (
					'status' => - 2 
			) );
			return;
		}
		// 更新用户数据
		$data ['userid'] = I ( 'userid' );
		$data ['username'] = I ( 'username' );
		$data ['phone'] = I ( 'phone' );
		$data ['cardid'] = I ( 'identity' );
		$data ['school'] = I ( 'school' );
		$data ['studentid'] = I ( 'stuno' );
		M ()->startTrans ();
		$ddb = M ( 'disposable' );
		if ($ddb->create ( $data ) != false) {
			$a = $ddb->add ();
			if ($a) {
				M ()->commit ();
				echo json_encode( array (
						'status' => 0 
				) );
			} else {
				M ()->rollback ();
				echo json_encode( array (
						'status' => - 1 
				) );
			}
		} else {
			echo json_encode( array (
					'status' => - 1 
			) );
		}
	}
	
	// 还款 本月和下月应还
	public function repayment() {
		$userid = I ( 'userid' );
		$date = time ();
		$map ['userid'] = $userid;
		$map ['hkstatus'] = array (
				'neq',
				1 
		);
		$map ['_string'] = "UNIX_TIMESTAMP(hktime)< $date ";
		$ben = M ( 'repayment' )->where ( $map )->sum ( 'hkmoney' );
		$map ['_string'] = "UNIX_TIMESTAMP(hktime)> $date ";
		$next = M ( 'repayment' )->where ( $map )->getField ( 'hkmoney' );
		$ben = $ben ? $ben : '0.00';
		$next = $next ? $next : '0.00';
		echo json_encode( array (
				'ben' => $ben,
				'next' => $next 
		) );
	}
	// 借款记录
	public function loanRecord() {
		$userid = I ( 'userid' );
		
		$res = M ( 'disposable' )->where ( array (
				'userid' => $userid 
		) )->field ( 'stime,auditing' )->find ();
		if ($res) {
			$time = date ( 'Y/m/d', $res ['stime'] );
			echo json_encode( array (
					'time' => $time,
					'status' => $res ['auditing'] 
			) );
		}
	}
	
	// 还款帐单
	public function refundBill() {
		$userid = I ( 'userid' );
		$res = M ( 'repayment' )->where ( array (
				'userid' => $userid 
		) )->order ( 'periods asc' )->select ();
		$time=time();
		foreach ($res as $k=>$v){
			if($time>strtotime($v['hktime'])){
				$res[$k]['hkstatus']='2';//过期未还
			}
		}
		echo json_encode( $res );
	}
	
	// 获取评价详情
	public function pingJiaDetail() {
		$orderid = I ( 'orderNo' );
		$res = M ( 'goods_sun' )->where ( array (
				'orderNo' => $orderid 
		) )->select ();
		echo json_encode( $res );
	}
	
    //查询订单是否有评价过
    public function isExistsPJ(){
        $orderid = I ( 'orderNo' );
        $map['orderNo']=$orderid;
        $map['_string']="unix_timestamp(now())-signTime<604800";
        $res = M ( 'goods_sun' )->where ($map)->count ();
        $this->ajaxReturn(array('count'=>$res));
    }
	

	//退款处理
	public function refundOrder(){
		$orderid=I('orderNo');
		$userid=I('userid');
		$orderInfo=M('orders')->where(array('orderId'=>$orderid))->find();
		if($orderInfo['orderStatus']==1||$orderInfo['orderStatus']==3){
			if($orderInfo['isRefund']>0){
				echo json_encode(array('status'=>-4));//已经申请过退款
				return;
			}
			M()->startTrans();
			$r=M('orders')->where(array('orderId'=>$orderid,'userId'=>$userid))->setField('isRefund',1);//退款中
			$data['orderid']=$orderid;
			$data['time']=time();
			$data['money']=$orderInfo['needPay'];
			$data['userid']=$orderInfo['userId'];
			$data['shopid']=$orderInfo['shopId'];
			$data['reason']='';
			$data['status']='0';
			$data['type']=2;//取消订单
			$s=M('refund')->data($data)->add();
			if($r!=false&&$s){
				M()->commit();
				echo json_encode(array('status'=>0));
			}else{
				M()->rollback();
				echo json_encode(array('status'=>-1));
			}
		}else{
			echo json_encode(array('status'=>-3));//订单状态已改变
		}
	}
	
	//商户同意或者拒绝退单
	public function refundOrderHandle(){
		$shopid=I('shopid');
		$orderid=I('orderid');
		$status=I('status');
		$isRefundHandle=M('orders')->where(array('orderId'=>$orderid))->getField('isRefund');
		$dq_orderStatus=M('orders')->where(array('orderId'=>$orderid))->getField('orderStatus');
		if($isRefundHandle>1){
			echo json_encode(array('status'=>-2));
			return;
		}
		if($status==1){
			$status=1;
		}else{
			$status=2;
		}
	 	//商家处理退款状态0退款中，1同意，2拒绝
		M()->startTrans();
		if($dq_orderStatus==-3) $dq_orderStatus=3;
		if($dq_orderStatus==-7) $dq_orderStatus=2;
		if($dq_orderStatus==-6) $dq_orderStatus=1;
		if($status==1) $a=M('refund')->where(array('orderid'=>$orderid))->setField(array('biz_status'=>$status));
		if($status==2) $a=M('refund')->where(array('orderid'=>$orderid))->setField(array('biz_status'=>$status,'beforeRefund'=>$dq_orderStatus));
		if($status==1){//同意
			$order_info=M('orders')->where(array('orderId'=>$orderid))->find();
			$user_id=$order_info['userId'];

			$user_info=M('users')->where(array('userId'=>$user_id))->find();;
			$money=$order_info['needPay'];
            $user_money=$user_info['userMoney']+$money;

			$result=M('users')->where(array('userId'=>$user_id))->setField(array('userMoney'=>$user_money));

			$time=time();
			$orderNo=$order_info['orderNo'];
            $data['type']='2';
            $data['money']=$money;
            $data['time']=$time;
            $data['orderNo']=$orderNo;
            $data['IncDec']='1';
            $data['userid']=$user_id;
            $data['balance']=$user_money;
            $data['remark']='订单退款';
            $data['payWay']='0';
            $result=M('money_record')->data($data)->add();
			$b=M('orders')->where(array('orderId'=>$orderid))->setField(array('isRefund'=>2,'orderStatus'=>-4));
		}else{//拒绝
			$b=M('orders')->where(array('orderId'=>$orderid))->setField(array('isRefund'=>1,'orderStatus'=>-5));
		}
		if($b!=false){
			M()->commit();
			echo json_encode(array('status'=>0));
		}else{
			M()->rollback();
			echo json_encode(array('status'=>-1));
		}
	}
	
	// 更新订单状态
	public function upAliPayResult() {
		$orderid = I ( 'orderNo' );
		$userid = I ( 'userid' );
		$payMoney = I ( 'payMoney' );
		$db = M ( 'orders' );
		$res = $db->where ( array (
				'orderId' => $orderid,
				'userId' => $userid 
		) )->setField ( 'isPay', 1 );
	}
	

	// 获取打印机要打印的信息
	public function printInfo() {
		$orderid = I ( 'orderid' );
		$order = M ( 'orders' )->where ( array (
				'orderId' => $orderid 
		) )->field ( 'shopId,deliverMoney,needPay,orderNo,totalMoney,createTime,orderId,isSelf,userName,userPhone,userAddress,requireTime,orderRemarks,FROM_UNIXTIME(payTime) as payTime' )->find ();
		$shopName = M ( 'shops' )->where ( array (
				'shopId' => $order ['shopId'] 
		) )->getField ( 'shopName' );
		$goods = M ( 'order_goods' )->where ( array (
				'orderId' => $orderid 
		) )->field ( 'goodsNums,goodsName,goodsPrice,goodsAttrName' )->select ();
		if ($goods) {
			foreach ( $goods as $k => $v ) {
				$goods [$k] ['singleTotal'] = $v ['goodsPrice'] * $v ['goodsNums'] . '元';
			}
		}
		//设置订单状态为已打印
		M('orders')->where(array('orderId'=>$orderid))->setField('isPrint',1);
		if($order ['isSelf']==0){
		    $order ['isSelf']='商家配送';
		}else if($order ['isSelf']==1){
		    $order ['isSelf']='自提';
		}else if($order ['isSelf']==-1){
		    $order ['isSelf']='无';
		}
		$order ['goods'] = $goods;
		$order ['shopName'] = $shopName;
		echo json_encode( $order );
	}
	// 打开App进场图片
	public function firstLoadApp() {
		$res = M ( 'animation' )->field ( 'url' )->limit ( 3 )->select ();
		echo json_encode( $res );
	}
	
	// 还款列表
	public function loanList() {
		$userid = I ( 'userid' );
		$date = time ();
		$map ['userid'] = $userid;
		$map ['hkstatus'] = array (
				'lt',
				1 
		);
		$map ['_string'] = "UNIX_TIMESTAMP(hktime)< $date ";
		$total = M ( 'repayment' )->where ( $map )->sum ( 'hkmoney' );
		$huan = M ( 'repayment' )->where ( $map )->order ( 'periods asc' )->select ();
		$num = count ( $huan );
		$res ['total'] = $total;
		$res ['info'] = $huan;
		$res ['num'] = $num;
		echo json_encode( $res );
	}
	
	// 单笔还款或者全额还款（余额）
	public function singleRefund() {
		$refundId = I ( 'refundId' );
		$refundType = I ( 'refundType' ); // 单笔还是全部一起还1单笔，2全部
		$userid = I ( 'userid' );
		$payMoney = I ( 'payMoney' );
		$payPwd = I ( 'payPwd' );
		$userid = I ( 'userid' );
		$uinfo = M ( 'users' )->where ( array (
				'userId' => $userid 
		) )->find ();
		if (md5 ( $payPwd . $uinfo ['loginSecret'] ) != $uinfo ['payPwd']) {
			// 支付密码错
			echo json_encode( array (
					'status' => - 2 
			) );
			return;
		}
		$payType = I ( 'payType' );
		$payTime = date ( 'Y-m-d H:i:s' );
		if ($refundType == 1) {
			if (! $refundId || ! $userid || ! $payMoney || ! isset ( $payType ) || $refundId == 'undefined' || $userid == 'undefined' || $payMoney == 'undefined') {
				echo json_encode( array (
						'status' => - 1 
				) );
				return;
			}
		} else {
			$refundId=explode('_', $refundId);
			if (! $userid || ! $payMoney || ! isset ( $payType ) || $userid == 'undefined' || $payMoney == 'undefined') {
				echo json_encode( array (
						'status' => - 1 
				) );
				return;
			}
		}

	  		M ()->startTrans ();
			// 减去用户的钱
			$r = M ( 'users' )->where ( array (
					'userId' => $userid 
			) )->setDec ( 'userMoney', $payMoney );
			// 更改订单状态为已付款
			if ( $r) {
				$b=false;
				// 更新贷款表数据
				$remark='';
				if ($refundType == 1) {
					$b = M ( 'repayment' )->where ( array (
							'userid' => $userid,
							'id' => $refundId 
					) )->setField ( array (
							'hkstatus' => 1 
					) );
					$remark=M('repayment')->where(array (
							'userid' => $userid,
							'id' => $refundId 
					))->getField('hktime');
					$remark.='日信用还款';
					if($b!=false){
						$b=true;
					}
				} else {
				
					$b = M ( 'repayment' )->where ( array (
							'userid' => $userid,
							'id' => array (
									'in',
									$refundId 
							) 
					) )->setField ( array (
							'hkstatus' => 1 
					) );
					$remark=M('repayment')->where(array (
							'userid' => $userid,
							'id' => array (
									'in',
									$refundId 
							) 
					))->getField('hktime',true);
					$count=count($remark);
					$remark=implode(',', $remark);
					$remark.="共".$count."期还款";
					if($b!=false){
						$b=true;
					}
				}
				$userinfo = M ( 'users' )->where ( array (
						'userId' => $userid 
				) )->find ();
				// 消费记录
				$c = $this->OperationMoneyRecord ( 7, $payMoney, $refundId, 0, $userid, $userinfo ['userMoney'],$remark,0 );
				if ($c && $b) {
					M ()->commit ();
					echo json_encode( array (
							'status' => 0 
					) );
					return;
				} else {
					M ()->rollback ();
					echo json_encode( array (
							'status' => - 1 
					) );
					return;
				}
			} else {
				M ()->rollback ();
				echo json_encode( array (
						'status' => - 1 
				) );
				return;
			}

	}
	
	// 充值下单
	public function topUp() {
		$userid = I ( 'userid' );
		$money = I ( 'money' );
		$db = M ( 'topUp' );
		$data ['money'] = $money;
		$data ['userid'] = $userid;
		$data ['time'] = date ( 'Y-m-d H:i:s', time () );
		$data ['out_trade_no'] = time ();
		$res = $db->data ( $data )->add ();
		if ($res) {
			echo json_encode( array (
					'orderNo' => $data ['out_trade_no'],
					'money' => $money,
					'status' => 0 
			) );
		} else {
			echo json_encode( array (
					'status' => - 1 
			) );
		}
	}
	
	// 发送手机验证码
	public function sendAuthCode() {
		$ip = get_client_ip ();
		$phone = trim ( I ( 'phone' ) );
		if (! preg_match ( '/^1[3|7|4|5|8]{1}\d{9}$/', $phone )) {
			// 手机号码不正确
			print_r ( json_encode ( array (
					'status' => - 1 
			) ) );
			return;
		}
		$map ['ip'] = $ip;
		$map ['phone'] = $phone;
		$map ['_logic'] = 'OR';
		$time = date ( 'Y-m-d', time () );
		$where ['_complex'] = $map;
		$where ['time'] = $time;
		$exists = M ( 'sendmes' )->where ( $where )->count ();
		if ($exists > 10) {
			// 每天获取的验证码数大于3次限制当天不能再发送
			print_r ( json_encode ( array (
					'status' => - 2 
			) ) );
			return;
		}
		$code = mt_rand ( 100000, 999999 );
		session ( array (
				'name' => 'session_id',
				'expire' => 600 
		) );
		session ( 'authCode', $code ); // 发送的验证码
		session ( 'authPhone', $phone ); // 对应的手机
		$cont = session ( 'authCode' ) . "(点点就到平台验证码,五分钟内有效）【点点就到】";
		$text = $cont;
		$data = array (
				'phone' => $phone,
				'ip' => $ip,
				'info' => $text,
				'time' => $time 
		);

		import("Vendor.yunsms");
	    $mes=new\yunsms;
	    $result=$mes->sendMsg($phone, $cont);
		if ($result['status'] == 0) {
			// 短信已经下发
			M ( 'sendmes' )->data ( $data )->add ();
			print_r ( json_encode ( array (
					'status' => 1,
					'authCode' => session ( 'authCode' ),
					'authPhone' => session ( 'authPhone' ) 
			) ) );
			return;
		} else {
			// 短信发送失败
			print_r ( json_encode ( array (
					'status' => 0 
			) ) );
			return;
		}
	}
	
	// 更改绑定手机号
	public function upBindPhone() {
		$userid = I ( 'userid' );
		$phone = I ( 'phone' );
		$db = M ( 'users' );
		$res = $db->where ( array (
				'userId' => $userid 
		) )->setField ( array (
				'userPhone' => $phone 
		) );
		if ($res != false) {
			echo json_encode( array (
					'status' => 0 
			) );
		} else {
			echo json_encode( array (
					'status' => - 1 
			) );
		}
	}
	
	public function like() {
		echo (microtime ());
		return;
		$sql = "
select * from (SELECT shopId,longitude,latitude,goodsCatId1,shopName,shopImg,deliveryStartMoney,deliveryFreeMoney,deliveryMoney,deliveryCostTime,serviceStartTime,serviceEndTime,
ROUND(6378.138*2*ASIN(SQRT(POW(SIN((23.148144*PI()/180-latitude*PI()/180)/2),2)+COS(23.148144*PI()/180)*COS(latitude*PI()/180)*POW(SIN((113.327456*PI()/180-longitude*PI()/180)/2),2)))*1000) AS juli
,(SELECT count(orderId) FROM oto_orders WHERE  isPay=1 and oto_orders.shopId=oto_shops.shopId) as monthNum FROM oto_shops where shopStatus=1 and shopAtive=1
  and hour(curtime())>=serviceStartTime and hour(curtime())<= serviceEndTime 
    ) as a 
  ORDER BY shopId DESC  
LIMIT 0,10
		";
		$m = new Model ();
		$res = $m->query ( $sql );
		echo $m->getLastSql ();
		//
		var_dump ( $res );
	}
	
	// 判断手机号是否注册
	
	// 获取用户信息
	public function getUserInfo() {
		$userid = I ( 'userid' );
		$file = "userSex,userName,userPhone,userScore,userPhoto,userMoney,trueName,identity,school,stuNo,isBiz,loginPwd,payPwd";
		$res = M ( 'users' )->field ( $file )->where(array('userId'=>$userid))->find ();
		if ($res ['loginPwd']) {
			$res ['loginPwd'] = 1;
		} else {
			$res ['loginPwd'] = 0;
		}
		if ($res ['payPwd']) {
			$res ['payPwd'] = 1;
		} else {
			$res ['payPwd'] = 0;
		}
		$res ['ip'] = get_client_ip ();
		echo json_encode( $res );
	}
	
	// 个人提现
	public function tiXian() {
		$userid = I ( 'userid' );
		$cardname = I ( 'cardname' );
		$bankname = I ( 'bankname' );
		$bankNum = I ( 'bankNum' );
		$money = I ( 'money' );
		$bankId=I('bankId');
		$uinfo = M ( 'users' )->where ( array (
				'userId' => $userid 
		) )->field ( 'loginSecret,payPwd,userMoney' )->find ();
		if($uinfo['userMoney']<$money){
			echo json_encode( array (
			'status' => - 1
			) );
			reurn;
		}
		$data ['userid'] = $userid;
		$data ['cardname'] = $cardname;
		$data ['bankname'] = $bankname;
		$data ['bankNum'] = $bankNum;
		$data ['money'] = $money;
		$data ['txtime'] = time ();
		$data ['txstatus'] = 0;
		$data ['bankId'] = $bankId;
		$data ['txNo'] = date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);;
		M ()->startTrans ();
		$res = M ( 'tixian' )->data ( $data )->add ();
		if ($res) {
			$balance = $uinfo ['userMoney'] - $money;
			$a = M ( 'users' )->where ( array (
					'userId' => $userid 
			) )->setDec ( 'userMoney', $money );
			$b = $this->OperationMoneyRecord ( 4, $money, $data ['txNo'], 0, $userid, $balance,'',0);
			if ($a && $b) {
				M ()->commit ();
				echo json_encode( array (
						'status' => 0 
				) );
			} else {
				echo json_encode( array (
						'status' => - 1 
				) );
				M ()->rollback ();
			}
		} else {
			echo json_encode( array (
					'status' => - 1 
			) );
			M ()->rollback ();
		}
	}
	
	//判断订单是否已经付款
	public function isPay(){
		$orderNo=I('orderNo');
		$res=M('orders')->where(array('orderNo'=>$orderNo))->getField('isPay');
		if($res){
			echo json_encode(array('ispay'=>1));
		}else{
			echo json_encode(array('ispay'=>0));
		}
	}
	
	// 删除地址
	public function delAddr() {
		$userid = I ( 'userid' );
		$id = I ( 'id' );
		$res = M ( 'userAddress' )->where ( array (
				'userId' => $userid,
				'addressId' => $id 
		) )->delete ();
		if ($res != false) {
			echo json_encode( array (
					'status' => 0 
			) );
		} else {
			echo json_encode( array (
					'status' => - 1 
			) );
		}
	}
	// 获取平台信息
	public function platformInfo() {
		$res = M ( 'sys_configs' )->field ( 'fieldName,fieldCode,fieldValue' )->select ();
		echo json_encode( $res );
	}
	
	// 获取店铺分类信息
	public function sort() {
		$res = M ( 'goods_cats' )->where(array('catFlag'=>1))->field ( 'catId,catName' )->select ();
		echo json_encode( $res );
	}
	
	// 根据店铺获取角色
	public function getRoleByBiz() {
		$userid = I ( 'userid' );
		$res = M ( 'role' )->where ( array (
				'userId' => $userid 
		) )->field ( 'id,rolename' )->select ();
		echo json_encode( $res );
	}
	
	// 商户APP上添加员工
	public function addStaff() {
		$userId = I ( 'userId' );//店主ID users表
		$telephone = I ( 'telephone' );
		$username = I ( 'username' );
		$password = I ( 'password' );
		$roleId = I ( 'roleId' );
		$isExisU = M ( 'users' )->where ( array (
				'bizPhone' => $telephone 
		) )->find ();
		$isExisS = M ( 'staff' )->where ( array (
				'telephone' => $telephone 
		) )->find ();
		if ($isExisU || $isExisS) {
			// 手机号被注册过了！
			echo json_encode( array (
					'status' => - 2 
			) );
			return;
		}
		$loginSecret = M ( 'users' )->field ( 'userId' )->where ( array (
				'userId' => $userId 
		) )->getField ( 'loginSecret' );
		$data ['userId'] = $userId;
		$data ['telephone'] = $telephone;
		$data ['username'] = $username;
		$data ['password'] = md5 ( $password . $loginSecret );
		$data ['roleId'] = $roleId;
		$r = M ( 'staff' )->data ( $data )->add ();
		if ($r) {
			echo json_encode( array (
					'status' => 0 
			) ); // 成功
			return;
		} else {
			echo json_encode( array (
					'status' => - 1 
			) ); // 失败
			return;
		}
	}
	
	// 接单3小时后自动确认订单
	public function autoComfirmOrder() {
		$time = time ();
		$threeHour = 10800;
		$map['orderStatus']=3;
		//$map['isRefund']=0;//退款状态为正常
		//$map ['_string'] = "($time-receiving)>$threeHour";
	    $map ['_string'] = "($time-receiving)>$threeHour and (isRefund=0 or isRefund=3)";
		$map['receiving']=array('gt',10);
		$db=M('orders');
	
		$info = $db->where ( $map )->field('orderId,needPay,shopId,redId')->select();
		$data=array();
		$shopDB=M('shops');
		foreach($info as $k=>$v){
		    M()->startTrans ();
		    //检查是否使用平台红包
		    $redMoney=0;
		    if($v['redId']>0){
		        $redMoney=M('red')->where(array('id'=>$v['redId']))->getField('redReduce');
		    }
			$A=$db->where(array('orderId'=>$v['orderId']))->setField(array('orderStatus'=>4,'signTime'=>time()));
			$B=$shopDB->where(array('shopId'=>$v['shopId']))->setInc('money',$v['needPay']+$redMoney);
			if($A&&$B){
			    M()->commit();
			}else{
			    M()->rollback();
			}
			$data[$k]['orderid']=$v['orderId'];
			$data[$k]['time']=time();
			$data[$k]['val']=4;
		}
		if(count($data)>0){
			M('autoComfirm')->addAll($data);
		}
	}
//获取银行卡列表
	public  function getBankList(){
		$res=M('banks')->where(array('bankFlag'=>1))->select();
		echo json_encode($res);
	}
	
	//获取常用提现帐户信息
	public  function getCommonAccount(){
	    $userid=I('userid');
	    $Info=M('tixian')->where(array('userid'=>$userid,'isdel'=>0))->field('bankId,bankname,bankNum,cardname')->group('bankNum')->select();
	    echo json_encode($Info);
	}
	
	//删除常用提现帐户信息
	public  function delCommonAccount(){
	    $userid=I('userid');
	    $bankNum=I('bankNum');
	    $Info=M('tixian')->where(array('userid'=>$userid,'bankNum'=>$bankNum))->setField(array('isdel'=>1));
	    if($Info){
	        echo json_encode(array('status'=>0));
	    }else{
	        echo json_encode(array('status'=>-1));
	    }
	}
	
	//测试极光推送
	//user可以是多个用户，用逗号隔开
	//alert为推送内容，title为标题，extras为自定义参数
	public function pushtouser($user=15815890001){      //$user,$alert,$title,$extras
		$userarray=explode(',',$user);
		try{
			$result = $this -> push -> push()
			->setPlatform(M\all)
			//->setAudience(M\all)
			->setAudience(M\audience(M\alias($userarray)))
			->setNotification(M\notification('你有新的订单需要处理！'))
			//->setNotification(M\notification(null, M\android($alert,$title,null,$extras)))
			->send();
		}catch (APIRequestException $e) {
	      
		}
	}
	
	//发短信队列添加到数据库
	public function  addSendQueue($phone,$orderNo){
	    $data['phone']=$phone;
	    $data['orderNo']=$orderNo;
	    $data['orderNo']=0;
	    M('sendmess_queue')->add($data);
	}
	
	
	public  function queueSendMess(){
	    $queue=M('sendmess_queue')->where(array('status'=>0))->limit(100)->select();
	    foreach ($queue as $k=>$v){
	        $res=$this->sendMessToBiz($v['phone'],$v['orderNo']);
	        $res=$this->sendMessToBiz('15115431966',$v['orderNo']);
	        if($res){
	            M('sendmess_queue')->where(array('id'=>$v['id']))->setField('status',1);
	            echo $v['phone'].'发送成功';
	        }else{
	            echo $v['phone'].'发送失败,秒后继续尝试';
	        }
	        sleep(10); //每隔十秒循环一次
	    }
	    echo '发送完毕';
	}
	
	//推送短信订单通知
	/**
	 * 
	 * @param number $phone 手机号
	 * @param string $orderNo 订单号
	 */
	public function sendMessToBiz($phone=15115431966,$orderNo='00000001'){
	    $cont="你有新的订单需要处理(订单号：$orderNo)【点点就到】";
	    /*$text = $cont;
	    $cont = urlencode ( $cont );
	    $url = "http://www.exincn.com/sms/api/index.asp?Action=send&SmsFlag=0&UserName=ddjd&UserPass=123123&Mobile={$phone}&Text=$cont";
	    $result = $this->Get ( $url );*/
		import("Vendor.yunsms");
	    $mes=new\yunsms;
	    $result=$mes->sendMsg($phone, $cont);
	}
	

	
	//微信订单支付异步通知处理
	public function WxPayNotice(){
	  vendor('WxPayPubHelper.WxPayConf_pub');
	  vendor('WxPayPubHelper.WxPayPubHelper');
	  $con=new \WxPayConf_pub(C('WxPayConf'));//配置信息
	  //使用通用通知接口
	  $notify = new \Notify_pub();
	  //存储微信的回调
	  $xml = $GLOBALS['HTTP_RAW_POST_DATA'];
	  $notify->saveData($xml);
	  $resultArr=$notify->data;
	  //验证签名，并回应微信。
	  //对后台通知交互时，如果微信收到商户的应答不是成功或超时，微信认为通知失败，
	  //微信会通过一定的策略（如30分钟共8次）定期重新发起通知，
	  //尽可能提高通知的成功率，但微信不保证通知最终能成功。
	  if($notify->checkSign() == FALSE){
	      $notify->setReturnParameter("return_code","FAIL");//返回状态码
	      $notify->setReturnParameter("return_msg","签名失败");//返回信息
	  }else{
	      $notify->setReturnParameter("return_code","SUCCESS");//设置返回码
	  }
	  $returnXml = $notify->returnXml();
	  //==商户根据实际情况设置相应的处理流程，此处仅作举例=======
	  if($notify->checkSign() == TRUE)
	  {
	      $out_trade_no =$resultArr['out_trade_no'];//订单号
	    
	      if ($notify->data["return_code"] == "FAIL") {
	          //此处应该更新一下订单状态，商户自行增删操作
	      }
	      elseif($notify->data["result_code"] == "FAIL"){
	          //此处应该更新一下订单状态，商户自行增删操作
	      }
	      else{//支付成功
	          //此处应该更新一下订单状态，商户自行增删操作
	          //开启事务
	          M()->startTrans ();
	          $tradeNo = $resultArr['transaction_id'];//流水号
	          $payMoney = $resultArr['total_fee']/100;
	          $notify_id = '';
	          $time=strtotime($resultArr['time_end']);
	          $notify_time = date('Y-m-d H:i:s',$time);
	          $buyer_email = $resultArr['openid']; // 买家帐号
	          $isPayInfo=M('orders')->where(array('orderNo'=>$out_trade_no))->field('isPay,userId,shopId')->find();
	          if($isPayInfo['isPay']){//已经付过
	              echo 'SUCCESS';return;
	          }
	          
	          //插入付款记录
	          $insertData['payType']=2;
	          $insertData['orderNo']=$out_trade_no;
	          $insertData['payTime']=$notify_time;
	          $insertData['tradeNo']=$tradeNo;
	          $insertData['payMoney']=$payMoney;
	          $insertData['userId']=$isPayInfo['userId'];
	          $insertData['type']=0;
	          $insertData['notify_id']=$notify_id;
	          $insertData['notify_time']=$notify_time;
	          $insertData['buyer_email']=$buyer_email;
	          $A=M('payRecord')->add($insertData);
	          
	          //更新订单信息
	          $updateDtate['payType']=2;
	          $updateDtate['isPay']=1;
	          $updateDtate['paytime']=strtotime($notify_time);
	         $B=M('orders')->where(array('orderNo'=>$out_trade_no))->save($updateDtate);

	          //消费积分
	          $score=floor($payMoney);
	          $xiaofei=M('scoreSetting')->getField('xiaofei');
	          if($xiaofei==-1){
	              $score = floor($payMoney);
	          }else{
	              $score = $xiaofei;
	          }
	          
	          $userinfo=M('users')->where(array('userId'=>$isPayInfo['userId']))->field('userScore,userTotalScore,userMoney')->find();
	          if($score>0){
	              //更新积分
	              $C=M('users')->where(array('userId'=>$isPayInfo['userId']))->setInc('userScore',$score);
	              $D=M('users')->where(array('userId'=>$isPayInfo['userId']))->setInc('userTotalScore',$score);
	              
	              //积分变动记录
	              $scoreData['userid']=$isPayInfo['userId'];
	              $scoreData['shopid']=$isPayInfo['shopId'];
	              $scoreData['orderid']=$out_trade_no;
	              $scoreData['score']=$score;
	              $scoreData['totalscore']=$userinfo['userScore']+$score;
	              $scoreData['time']=$time;
	              $scoreData['ip']='';
	              $scoreData['IncDec']=1;
	              $scoreData['type']=1;
	              $E=M('scoreRecord')->add($scoreData);
	              
	          }
	          
	          //余额变动记录
	          $balanceData['actionType']=1;
	          $balanceData['money']=$payMoney;
	          $balanceData['time']=$time;
	          $balanceData['ip']='';
	          $balanceData['orderid']=$out_trade_no;
	          $balanceData['IncDec']=0;
	          $balanceData['userid']=$isPayInfo['userId'];
	          $balanceData['balance']=$userinfo['userMoney'];
	          $balanceData['remark']='';
	          $balanceData['payWay']=2;
	          $F=M('moneyRecord')->add($balanceData);
	        
	          if($score>0){
	              if($A&&$B!=FALSE&&$C&&$D&&$E&&$F){
	                   M()->commit();
	                   echo 'SUCCESS';
	                   $this->checkStock(0,$out_trade_no,0);
	                   //发送极光推送
	                   $bizInfo = M ( 'users' )->where ( array (
	                       's.shopId' => $isPayInfo ['shopId']
	                   ) )->join ( 'as u left join oto_shops as s on u.userId=s.userId' )->field ( 'u.bizPhone' )->find ();
	                   if($bizInfo){
	                       $this->pushtouser($bizInfo['bizPhone']);
	                      try {
	                          $this->sendMessToBiz($bizInfo['bizPhone'],$out_trade_no);
	                          $this->sendMessToBiz('15115431966',$out_trade_no);
							  $this->sendMessToBiz('13469135911',$out_trade_no);
	                      } catch (Exception $e) {
	                          
	                      }
	                      
	                   }
	              }else{
	                  M()->rollback();
	                  echo 'FAIL';
	              }
	          }else{
	              if($A&&$B!=FALSE&&$F){
	                  M()->commit();
	                  $this->checkStock(0,$out_trade_no,0);
	                  echo 'SUCCESS';
	                  //发送极光推送
	                  $bizInfo = M ( 'users' )->where ( array (
	                      's.shopId' => $isPayInfo ['shopId']
	                  ) )->join ( 'as u left join oto_shops as s on u.userId=s.userId' )->field ( 'u.bizPhone' )->find ();
	                  if($bizInfo){
	                      $this->pushtouser($bizInfo['bizPhone']);
	                      try {
	                          $this->sendMessToBiz($bizInfo['bizPhone'],$out_trade_no);
	                          $this->sendMessToBiz('15115431966',$out_trade_no);
							  $this->sendMessToBiz('13469135911',$out_trade_no);
	                      } catch (Exception $e) {
	                      }
	                     
	                  }
	              }else{
	                  M()->rollback();
	                  echo 'FAIL';
	              }
	          }
	         // echo $returnXml;
	      }
	      //商户自行增加处理流程,
	      //例如：更新订单状态
	      //例如：数据库操作
	      //例如：推送支付完成信息
	  }
	}
	
	//微信充值异步通知处理
	public function WxTopUpNotice(){
	    vendor('WxPayPubHelper.WxPayConf_pub');
	    vendor('WxPayPubHelper.WxPayPubHelper');
	    $con=new \WxPayConf_pub(C('WxPayConf'));//配置信息
	    
	    //使用通用通知接口
	    $notify = new \Notify_pub();
	     
	    //存储微信的回调
	    $xml = $GLOBALS['HTTP_RAW_POST_DATA'];
	    $notify->saveData($xml);
	    $resultArr=$notify->data;
	    //验证签名，并回应微信。
	    //对后台通知交互时，如果微信收到商户的应答不是成功或超时，微信认为通知失败，
	    //微信会通过一定的策略（如30分钟共8次）定期重新发起通知，
	    //尽可能提高通知的成功率，但微信不保证通知最终能成功。
	    if($notify->checkSign() == FALSE){
	        $notify->setReturnParameter("return_code","FAIL");//返回状态码
	        $notify->setReturnParameter("return_msg","签名失败");//返回信息
	    }else{
	        $notify->setReturnParameter("return_code","SUCCESS");//设置返回码
	    }
	    $returnXml = $notify->returnXml();
	    //==商户根据实际情况设置相应的处理流程，此处仅作举例=======
	    if($notify->checkSign() == TRUE)
	    {
	       
	        if ($notify->data["return_code"] == "FAIL") {
	            //此处应该更新一下订单状态，商户自行增删操作
	        }
	        elseif($notify->data["result_code"] == "FAIL"){
	            //此处应该更新一下订单状态，商户自行增删操作
	        }
	        else{//支付成功
	            //此处应该更新一下订单状态，商户自行增删操作
	            //开启事务
	            M()->startTrans();
	            $out_trade_no =$resultArr['out_trade_no'];//订单号
	            $tradeNo = $resultArr['transaction_id'];//流水号
	            $payMoney = $resultArr['total_fee']/100;
	            $notify_id = '';
	            $time=strtotime($resultArr['time_end']);
	            $notify_time = date('Y-m-d H:i:s',$time);
	            $buyer_email = $resultArr['openid']; // 买家帐号
	            $isPayInfo=M('topUp')->where(array('out_trade_no'=>$out_trade_no))->field('status,userid')->find();
	            if($isPayInfo['status']){//已充值
	                echo 'SUCCESS';
	                return;
	            }
	             $balance=M('users')->where(array('userId'=>$isPayInfo['userid']))->getField('userMoney');
	             $newBalance=$balance+$payMoney;
	             
	             $payRecord['payType']=2;
	             $payRecord['orderNo']=$out_trade_no;
	             $payRecord['payTime']=$notify_time;
	             $payRecord['tradeNo']=$tradeNo;
	             $payRecord['payMoney']=$payMoney;
	             $payRecord['userId']=$isPayInfo['userid'];
	             $payRecord['type']=0;
	             $payRecord['notify_id']=$notify_id;
	             $payRecord['notify_time']=$notify_time;
	             $payRecord['buyer_email']=$buyer_email;
	             
	             $A=M('payRecord')->add($payRecord);
	             
	             $B=M('users')->where(array('userId'=>$isPayInfo['userid']))->setInc('userMoney',$payMoney);
	        
	             $C=M('topUp')->where(array('out_trade_no'=>$out_trade_no))->setField('status',1);
	              
	             //余额变动记录
	             $moneyRecord['actionType']=3;
	             $moneyRecord['money']=$payMoney;
	             $moneyRecord['time']=$time;
	             $moneyRecord['ip']='';
	             $moneyRecord['orderid']=$out_trade_no;
	             $moneyRecord['IncDec']=1;
	             $moneyRecord['userid']=$isPayInfo['userid'];
	             $moneyRecord['balance']=$newBalance;
	             $moneyRecord['remark']='';
	             $moneyRecord['payWay']=2;
	             $D=M('moneyRecord')->add($moneyRecord);
	             if($A&&$B&&$C&&$D){
	                 M()->commit();
	                 echo 'SUCCESS';
	             }else{
	                 M()->rollback();
	                 echo 'FAIL';
	             }
	            // echo $returnXml;
	        }
	    }
	}
	
	//微信还款通知处理
	public function WxRefundNotice(){
	    vendor('WxPayPubHelper.WxPayConf_pub');
	    vendor('WxPayPubHelper.WxPayPubHelper');
	    $con=new \WxPayConf_pub(C('WxPayConf'));//配置信息
	     
	    //使用通用通知接口
	    $notify = new \Notify_pub();
	
	    //存储微信的回调
	    $xml = $GLOBALS['HTTP_RAW_POST_DATA'];
	    $notify->saveData($xml);
	    $resultArr=$notify->data;
	    //验证签名，并回应微信。
	    //对后台通知交互时，如果微信收到商户的应答不是成功或超时，微信认为通知失败，
	    //微信会通过一定的策略（如30分钟共8次）定期重新发起通知，
	    //尽可能提高通知的成功率，但微信不保证通知最终能成功。
	    if($notify->checkSign() == FALSE){
	        $notify->setReturnParameter("return_code","FAIL");//返回状态码
	        $notify->setReturnParameter("return_msg","签名失败");//返回信息
	    }else{
	        $notify->setReturnParameter("return_code","SUCCESS");//设置返回码
	    }
	    $returnXml = $notify->returnXml();
	    //==商户根据实际情况设置相应的处理流程，此处仅作举例=======
	    if($notify->checkSign() == TRUE)
	    {
	
	        if ($notify->data["return_code"] == "FAIL") {
	            //此处应该更新一下订单状态，商户自行增删操作
	        }
	        elseif($notify->data["result_code"] == "FAIL"){
	            //此处应该更新一下订单状态，商户自行增删操作
	        }
	        else{//支付成功
	            //此处应该更新一下订单状态，商户自行增删操作
	            //开启事务
	            M()->startTrans();
	            $out_trade_no =$resultArr['out_trade_no'];//订单号
	            $tradeNo = $resultArr['transaction_id'];//流水号
	            $payMoney = $resultArr['total_fee']/100;
	            $notify_id = '';
	            $time=strtotime($resultArr['time_end']);
	            $notify_time = date('Y-m-d H:i:s',$time);
	            $buyer_email = $resultArr['openid']; // 买家帐号
	            
	            $type = $out_trade_no [0];
	            $sql = "";
	            if ($type == 'A') { // 单笔还款
	                $out_trade_no = ltrim ( $out_trade_no, 'A' );
	                $sql = "select * from oto_repayment where id=$out_trade_no";
	            } else if ($type == "B") { // 全部还款
	                $out_trade_no = ltrim ( $out_trade_no, 'B' );
	                $ids = '';
	                $temp = explode ( '_', $out_trade_no );
	                foreach ( $temp as $k => $v ) {
	                    $ids .= $v . ',';
	                }
	                $ids = rtrim ( $ids, ',' );
	                $sql = "select * from oto_repayment where id in ($ids)";
	            } else {
	                echo 'FAIL';
	                return;
	            }
	            
	            $res=M()->query($sql);
	            $userid = $res [0] ['userid'];
	            if ($res [0] ['hkstatus'] == 1) { // 已经更新过状态了
	                echo 'SUCCESS';
	                return;
	            }
	            $totalMoney = 0;
	            foreach ( $res as $kk => $vv ) {
	                $totalMoney += $vv ['hkmoney'];
	            }
	            
	            $insertSql = "INSERT INTO `oto_pay_record` (`payType`, `orderNo`, `payTime`, `tradeNo`, `payMoney`, `userId`, `type`, `notify_id`, `notify_time`, `buyer_email`) VALUES ('2', '$out_trade_no', '$notify_time','$tradeNo', '$payMoney', '$userid', '1', '$notify_id', '$notify_time', '$buyer_email')";
	            $A=M()->query($insertSql);
	            
	            $updateSql = "";
	            if ($type == 'A') {
	                $updateSql = "UPDATE `oto_repayment` SET `hkstatus`='1' WHERE (`id`='$out_trade_no')";
	            } else if ($type == 'B') {
	                $updateSql = "UPDATE `oto_repayment` SET `hkstatus`='1' WHERE `id` in($ids)";
	            }
	            
	            $B=M()->query($updateSql);
	            
	            $balance=M('users')->where(array('userId'=>$userid))->getField('userMoney');
	            
	            $insertTorecord="INSERT INTO `oto_money_record` (`actionType`, `money`, `time`, `ip`, `orderid`, `IncDec`, `userid`, `balance`,`remark`, `payWay`) VALUES ('7', '$payMoney', '$time', '', '$out_trade_no', '0', '$userid', '$balance','',2)";
	            $C=M()->query($insertTorecord);
	            
	            if($A&&$B&&$C){
	                M()->commit();
	                echo 'SUCCESS';
	            }else{
	                M()->rollback();
	                echo 'FAIL';
	            }
	            // echo $returnXml;
	        }
	    }
	}
	
	//支付宝订单异步通知处理
	public function AliPayNotice() {
	    vendor ( 'Alipay.Corefunction' );
	    vendor ( 'Alipay.Notify' );
	    vendor ( 'Alipay.Rsa' );
	    // 计算得出通知验证结果
	    $alipayNotify = new \AlipayNotify (C('alipay_config'));
	    $verify_result = $alipayNotify->verifyNotify ();
	   // goto noValidtae;
	    if ($verify_result) { // 验证成功
	        // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	        // 请在这里加上商户的业务逻辑程序代
	
	        // ——请根据您的业务逻辑来编写程序（以下代码仅作参考）——
	
	        // 获取支付宝的通知返回参数，可参考技术文档中服务器异步通知参数列表
	
	        if ($_POST ['trade_status'] == 'TRADE_FINISHED') {
	            // 判断该笔订单是否在商户网站中已经做过处理
	            // 如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
	            // 如果有做过处理，不执行商户的业务程序
	
	            // 注意：
	            // 退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
	            // 请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
	
	            // 调试用，写文本函数记录程序运行情况是否正常
	            // logResult("这里写入想要调试的代码变量值，或其他运行的结果记录");
	        } else if ($_POST ['trade_status'] == 'TRADE_SUCCESS') {
	            // 判断该笔订单是否在商户网站中已经做过处理
	            // 如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
	            // 如果有做过处理，不执行商户的业务程序
	            // M('alipaytest')->data(array('out_trade_no'=>$out_trade_no,'trade_no'=>$trade_no,'time'=>date('Y-m-d H:i:s')))->add();
	            // 注意：
	            // 付款完成后，支付宝系统发送该交易状态通知
	            // 请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
	
	            // 调试用，写文本函数记录程序运行情况是否正常
	            //noValidtae:
	            M()->startTrans ();
	            $out_trade_no =$_POST['out_trade_no'];//订单号
	            $tradeNo = $_POST['trade_no'];//流水号
	            $payMoney = $_POST['total_fee'];
	            $notify_id = $_POST ['notify_id'];
	            $time=strtotime($_POST ['notify_time']);
	            $notify_time = $_POST ['notify_time'];
	            $buyer_email = $_POST ['buyer_email']; // 买家帐号
	            $isPayInfo=M('orders')->where(array('orderNo'=>$out_trade_no))->field('isPay,userId,shopId')->find();
	            if($isPayInfo['isPay']){//已经付过
	                echo 'SUCCESS';return;
	            }
	            //插入付款记录
	            $insertData['payType']=1;
	            $insertData['orderNo']=$out_trade_no;
	            $insertData['payTime']=$notify_time;
	            $insertData['tradeNo']=$tradeNo;
	            $insertData['payMoney']=$payMoney;
	            $insertData['userId']=$isPayInfo['userId'];
	            $insertData['type']=0;
	            $insertData['notify_id']=$notify_id;
	            $insertData['notify_time']=$notify_time;
	            $insertData['buyer_email']=$buyer_email;
	            $A=M('payRecord')->add($insertData);
	
	            //更新订单信息
	            $updateDtate['payType']=1;
	            $updateDtate['isPay']=1;
	            $updateDtate['paytime']=strtotime($notify_time);
	            $B=M('orders')->where(array('orderNo'=>$out_trade_no))->save($updateDtate);
	             
	            //消费积分
	            $score=floor($payMoney);
	            $xiaofei=M('scoreSetting')->getField('xiaofei');
	            if($xiaofei==-1){
	                $score = floor($payMoney);
	            }else{
	                $score = $xiaofei;
	            }
	
	            $userinfo=M('users')->where(array('userId'=>$isPayInfo['userId']))->field('userScore,userTotalScore,userMoney')->find();
	            if($score>0){
	                //更新积分
	                $C=M('users')->where(array('userId'=>$isPayInfo['userId']))->setInc('userScore',$score);
	                $D=M('users')->where(array('userId'=>$isPayInfo['userId']))->setInc('userTotalScore',$score);
	
	                //积分变动记录
	                $scoreData['userid']=$isPayInfo['userId'];
	                $scoreData['shopid']=$isPayInfo['shopId'];
	                $scoreData['orderid']=$out_trade_no;
	                $scoreData['score']=$score;
	                $scoreData['totalscore']=$userinfo['userScore']+$score;
	                $scoreData['time']=$time;
	                $scoreData['ip']='';
	                $scoreData['IncDec']=1;
	                $scoreData['type']=1;
	                $E=M('scoreRecord')->add($scoreData);
	
	            }
	
	            //余额变动记录
	            $balanceData['actionType']=1;
	            $balanceData['money']=$payMoney;
	            $balanceData['time']=$time;
	            $balanceData['ip']='';
	            $balanceData['orderid']=$out_trade_no;
	            $balanceData['IncDec']=0;
	            $balanceData['userid']=$isPayInfo['userId'];
	            $balanceData['balance']=$userinfo['userMoney'];
	            $balanceData['remark']='';
	            $balanceData['payWay']=1;
	            $F=M('moneyRecord')->add($balanceData);
	
	            if($score>0){
	                if($A&&$B!=FALSE&&$C&&$D&&$E&&$F){
	                    M()->commit();
	                    echo 'SUCCESS';
	                    $this->checkStock(0,$out_trade_no,0);
	                    //发送极光推送
	                    $bizInfo = M ( 'users' )->where ( array (
	                        's.shopId' => $isPayInfo ['shopId']
	                    ) )->join ( 'as u left join oto_shops as s on u.userId=s.userId' )->field ( 'u.bizPhone' )->find ();
	                    if($bizInfo){
	                        $this->pushtouser($bizInfo['bizPhone']);
	                        try {
	                            $this->sendMessToBiz($bizInfo['bizPhone'],$out_trade_no);
	                            $this->sendMessToBiz('15115431966',$out_trade_no);
								$this->sendMessToBiz('13469135911',$out_trade_no);
	                        } catch (Exception $e) {
	                        }
	                       
	                    }
	                }else{
	                    M()->rollback();
	                    echo 'FAIL';
	                }
	            }else{
	                if($A&&$B!=FALSE&&$F){
	                    M()->commit();
	                    echo 'SUCCESS';
	                    $this->checkStock(0,$out_trade_no,0);
	                    //发送极光推送
	                    $bizInfo = M ( 'users' )->where ( array (
	                        's.shopId' => $isPayInfo ['shopId']
	                    ) )->join ( 'as u left join oto_shops as s on u.userId=s.userId' )->field ( 'u.bizPhone' )->find ();
	                    if($bizInfo){
	                        $this->pushtouser($bizInfo['bizPhone']);
	                        try {
	                            $this->sendMessToBiz($bizInfo['bizPhone'],$out_trade_no);
	                            $this->sendMessToBiz('15115431966',$out_trade_no);
	                        } catch (Exception $e) {
	                        }
	                        
	                    }
	                }else{
	                    M()->rollback();
	                    echo 'FAIL';
	                }
	            }
	            logResult ( "到这里成功" );
	        }
	        	
	        // ——请根据您的业务逻辑来编写程序（以上代码仅作参考）——
	        	
	        //echo 'SUCCESS';// 请不要修改或删除
	
	        // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	    } else {
	        	
	        // 验证失败
	        // 调试用，写文本函数记录程序运行情况是否正常
	        echo 'FAIL';
	    }
	}
	
	//支付宝充值异步通知 
	public function AliPayTopUpNotice(){
	    vendor ( 'Alipay.Corefunction' );
	    vendor ( 'Alipay.Notify' );
	    vendor ( 'Alipay.Rsa' );
	    // 计算得出通知验证结果
	    $alipayNotify = new \AlipayNotify (C('alipay_config'));
	    $verify_result = $alipayNotify->verifyNotify ();
	    //goto noValidtae;
	    if ($verify_result) { // 验证成功
	        // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	        // 请在这里加上商户的业务逻辑程序代
	    
	        // ——请根据您的业务逻辑来编写程序（以下代码仅作参考）——
	    
	        // 获取支付宝的通知返回参数，可参考技术文档中服务器异步通知参数列表
	    
	        if ($_POST ['trade_status'] == 'TRADE_FINISHED') {
	            // 判断该笔订单是否在商户网站中已经做过处理
	            // 如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
	            // 如果有做过处理，不执行商户的业务程序
	    
	            // 注意：
	            // 退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
	            // 请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
	    
	            // 调试用，写文本函数记录程序运行情况是否正常
	            // logResult("这里写入想要调试的代码变量值，或其他运行的结果记录");
	        } else if ($_POST ['trade_status'] == 'TRADE_SUCCESS') {
	            // 判断该笔订单是否在商户网站中已经做过处理
	            // 如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
	            // 如果有做过处理，不执行商户的业务程序
	            // M('alipaytest')->data(array('out_trade_no'=>$out_trade_no,'trade_no'=>$trade_no,'time'=>date('Y-m-d H:i:s')))->add();
	            // 注意：
	            // 付款完成后，支付宝系统发送该交易状态通知
	            // 请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
	    
	            // 调试用，写文本函数记录程序运行情况是否正常
	            //noValidtae:
	            M()->startTrans();
	            $out_trade_no =$_POST['out_trade_no'];//订单号
			    $tradeNo = $_POST['trade_no'];//流水号
			    $payMoney = $_POST['total_fee'];
			    $notify_id = $_POST ['notify_id'];
			    $time=strtotime($_POST ['notify_time']);
			    $notify_time = $_POST ['notify_time'];
			    $buyer_email = $_POST ['buyer_email']; // 买家帐号
	            $isPayInfo=M('topUp')->where(array('out_trade_no'=>$out_trade_no))->field('status,userid')->find();
	            if($isPayInfo['status']){//已充值
	                echo 'SUCCESS';
	                return;
	            }
	            $balance=M('users')->where(array('userId'=>$isPayInfo['userid']))->getField('userMoney');
	            $newBalance=$balance+$payMoney;
	            $payRecord['payType']=1;
	            $payRecord['orderNo']=$out_trade_no;
	            $payRecord['payTime']=$notify_time;
	            $payRecord['tradeNo']=$tradeNo;
	            $payRecord['payMoney']=$payMoney;
	            $payRecord['userId']=$isPayInfo['userid'];
	            $payRecord['type']=0;
	            $payRecord['notify_id']=$notify_id;
	            $payRecord['notify_time']=$notify_time;
	            $payRecord['buyer_email']=$buyer_email;
	            
	            $A=M('payRecord')->add($payRecord);
	            
	            $B=M('users')->where(array('userId'=>$isPayInfo['userid']))->setInc('userMoney',$payMoney);
	             
	            $C=M('topUp')->where(array('out_trade_no'=>$out_trade_no))->setField('status',1);
	             
	            //余额变动记录
	            $moneyRecord['actionType']=3;
	            $moneyRecord['money']=$payMoney;
	            $moneyRecord['time']=$time;
	            $moneyRecord['ip']='';
	            $moneyRecord['orderid']=$out_trade_no;
	            $moneyRecord['IncDec']=1;
	            $moneyRecord['userid']=$isPayInfo['userid'];
	            $moneyRecord['balance']=$newBalance;
	            $moneyRecord['remark']='';
	            $moneyRecord['payWay']=1;
	            $D=M('moneyRecord')->add($moneyRecord);
	            if($A&&$B&&$C&&$D){
	                M()->commit();
	                echo 'SUCCESS';
	            }else{
	                M()->rollback();
	                echo 'FAIL';
	            }
	            
	        }
	        	
	        // ——请根据您的业务逻辑来编写程序（以上代码仅作参考）——
	        	
	        //echo 'SUCCESS';// 请不要修改或删除
	    
	        // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	    } else {
	        	
	        // 验证失败
	        // 调试用，写文本函数记录程序运行情况是否正常
	        echo 'FAIL';
	    }
	    
	}
	//支付宝还款异步通知
	public function AliPayRefundNotice(){
	    
	    vendor ( 'Alipay.Corefunction' );
	    vendor ( 'Alipay.Notify' );
	    vendor ( 'Alipay.Rsa' );
	    // 计算得出通知验证结果
	    $alipayNotify = new \AlipayNotify (C('alipay_config'));
	    $verify_result = $alipayNotify->verifyNotify ();
	    //goto noValidtae;
	    if ($verify_result) { // 验证成功
	        // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	        // 请在这里加上商户的业务逻辑程序代
	         
	        // ——请根据您的业务逻辑来编写程序（以下代码仅作参考）——
	         
	        // 获取支付宝的通知返回参数，可参考技术文档中服务器异步通知参数列表
	         
	        if ($_POST ['trade_status'] == 'TRADE_FINISHED') {
	            // 判断该笔订单是否在商户网站中已经做过处理
	            // 如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
	            // 如果有做过处理，不执行商户的业务程序
	             
	            // 注意：
	            // 退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
	            // 请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
	             
	            // 调试用，写文本函数记录程序运行情况是否正常
	            // logResult("这里写入想要调试的代码变量值，或其他运行的结果记录");
	        } else if ($_POST ['trade_status'] == 'TRADE_SUCCESS') {
	            // 判断该笔订单是否在商户网站中已经做过处理
	            // 如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
	            // 如果有做过处理，不执行商户的业务程序
	            // M('alipaytest')->data(array('out_trade_no'=>$out_trade_no,'trade_no'=>$trade_no,'time'=>date('Y-m-d H:i:s')))->add();
	            // 注意：
	            // 付款完成后，支付宝系统发送该交易状态通知
	            // 请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
	             
	            // 调试用，写文本函数记录程序运行情况是否正常
	           //noValidtae:
	            M()->startTrans();
	            $out_trade_no =$_POST['out_trade_no'];//订单号
	            $tradeNo = $_POST['trade_no'];//流水号
	            $payMoney = $_POST['total_fee'];
	            $notify_id = $_POST ['notify_id'];
	            $time=strtotime($_POST ['notify_time']);
	            $notify_time = $_POST ['notify_time'];
	            $buyer_email = $_POST ['buyer_email']; // 买家帐号
	            $type = $out_trade_no [0];
	            $sql = "";
	            if ($type == 'A') { // 单笔还款
	                $out_trade_no = ltrim ( $out_trade_no, 'A' );
	                $sql = "select * from oto_repayment where id=$out_trade_no";
	            } else if ($type == "B") { // 全部还款
	                $out_trade_no = ltrim ( $out_trade_no, 'B' );
	                $ids = '';
	                $temp = explode ( '_', $out_trade_no );
	                foreach ( $temp as $k => $v ) {
	                    $ids .= $v . ',';
	                }
	                $ids = rtrim ( $ids, ',' );
	                $sql = "select * from oto_repayment where id in ($ids)";
	            } else {
	                echo 'FAIL';
	                return;
	            }
	            $res=M()->query($sql);
	            $userid = $res [0] ['userid'];
	            if ($res [0] ['hkstatus'] == 1) { // 已经更新过状态了
	                echo 'SUCCESS';
	                return;
	            }
	            $totalMoney = 0;
	            foreach ( $res as $kk => $vv ) {
	                $totalMoney += $vv ['hkmoney'];
	            }
	             
	            $insertSql = "INSERT INTO `oto_pay_record` (`payType`, `orderNo`, `payTime`, `tradeNo`, `payMoney`, `userId`, `type`, `notify_id`, `notify_time`, `buyer_email`) VALUES ('2', '$out_trade_no', '$notify_time','$tradeNo', '$payMoney', '$userid', '1', '$notify_id', '$notify_time', '$buyer_email')";
	            $A=M()->query($insertSql);
	             
	            $updateSql = "";
	            if ($type == 'A') {
	                $updateSql = "UPDATE `oto_repayment` SET `hkstatus`='1' WHERE (`id`='$out_trade_no')";
	            } else if ($type == 'B') {
	                $updateSql = "UPDATE `oto_repayment` SET `hkstatus`='1' WHERE `id` in($ids)";
	            }
	             
	            $B=M()->query($updateSql);
	             
	            $balance=M('users')->where(array('userId'=>$userid))->getField('userMoney');
	             
	            $insertTorecord="INSERT INTO `oto_money_record` (`actionType`, `money`, `time`, `ip`, `orderid`, `IncDec`, `userid`, `balance`,`remark`, `payWay`) VALUES ('7', '$payMoney', '$time', '', '$out_trade_no', '0', '$userid', '$balance','',1)";
	            $C=M()->query($insertTorecord);
	             
	            if($A&&$B&&$C){
	                M()->commit();
	                echo 'SUCCESS';
	            }else{
	                M()->rollback();
	                echo 'FAIL';
	            }
	             
	        }
	        // ——请根据您的业务逻辑来编写程序（以上代码仅作参考）——
	    
	        //echo 'SUCCESS';// 请不要修改或删除
	         
	        // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	    } else {
	    
	        // 验证失败
	        // 调试用，写文本函数记录程序运行情况是否正常
	        echo 'FAIL';
	    }
	    
	}
	

	//付款成功后操作库存
	//$type操作1为加库存，0为减库存
	/**
	 * 构造函数
	 * @param $type 操作1为加库存，0为减库存
	 */
	public function checkStock($orderID=0,$orderNo=0,$type=0){
	    if($orderID){
	        $id=$orderID;
	    }else{
	        $map['orderNo']=$orderNo;
	        $id=M('orders')->where($map)->getField('orderId');
	    }
	    $info=M('order_goods')->where(array('orderId'=>$id))->field('goodsId,goodsNums')->select();
	    $db=M('goods');
	    if($type==1){
	        foreach ($info as $k=>$v){
	            $db->where(array('goodsId'=>$v['goodsId']))->setInc('goodsStock',$v['goodsNums']);
	        }
	    }else{
	        foreach ($info as $k=>$v){
	            $db->where(array('goodsId'=>$v['goodsId']))->setDec('goodsStock',$v['goodsNums']);
	        }
	    }
	}
	//付款时检查库存, 营业时间，店铺状态，订单状态
	public function Stock(){
	    $orderid=I('orderId');
	    //订单状态   //检测订单是否已付款
	    $orderInfo=M('orders')->where(array('orderId'=>$orderid))->find();
	    if($orderInfo['isPay']==1){
	        $this->ajaxReturn(array('status'=>-2,'msg'=>'订单状态已改变'));return;
	    }
	    //店铺状态
	    $shopInfo=M('shops')->where(array('shopId'=>$orderInfo['shopId']))->find();
	    if($shopInfo['shopFlag']!=1||$shopInfo['shopStatus']!=1){
	        $this->ajaxReturn(array('status'=>-3,'msg'=>'店铺状态异常！'));return;
	    }
	    //检查营业时间
	    $S1=$shopInfo['serviceStartTime'];
	    $E1=$shopInfo['serviceEndTime'];
	    $S2=$shopInfo['serviceStartTime2'];
	    $E2=$shopInfo['serviceEndTime2'];
	    $H=intval(date('G'));
	    $status=false;
	    if($S1>$E1){
	        if($H>=$S1){//当前时间大于开始时间
	            $status=true;
	        }else if($E1>$H) {//结束时间大于当前时间
	            $status=true;
	        }
	    }else{
	        //当前时间在开始和结束之间
	        if($S1==0&&$E1==0){
	    
	        }else{
	            if($H>=$S1&&$H<$E1){
	                $status=true;
	            }
	        }
	    }
	    if(!$status){
	        if($S2>$E2){
	            if($H>=$S2){//当前时间大于开始时间
	                $status=true;
	            }else if($E2>$H) {//结束时间大于当前时间
	                $status=true;
	            }
	        }else{
	            //当前时间在开始和结束之间
	            if($S2==0&&$E2==0){
	    
	            }else{
	                if($H>=$S2&&$H<$E2){
	                    $status=true;
	                }
	            }
	        }
	    }
	    //休息中，或者非店铺营业时间
	    if(!$status||$shopInfo['shopAtive'] == 0){
	        if(!$status){
	            $this->ajaxReturn(array('status'=>-4,'msg'=>'非营业时间！'));return;
	        }
	        if($shopInfo['shopAtive'] == 0){
	            $this->ajaxReturn(array('status'=>-5,'msg'=>'店铺打烊啦！'));return;
	        }
	    }
	    
	    //检查库存
	    $info=M('order_goods')->where(array('orderId'=>$orderid))->field('goodsId,goodsNums')->select();
	    $ids=M('order_goods')->where(array('orderId'=>$orderid))->getField('goodsId',true);
	    $goodsField='goodsStock,goodsId';
	    $goodsInfo=M('goods')->where(array('goodsId'=>array('in',$ids))) ->field($goodsField)->select();
	    //缺货产品和实际库存
	    $i=0;
	    foreach ($goodsInfo as $k=>$v){
	        foreach($info as $kk=>$vv){
	            if($vv['goodsId']==$v['goodsId']){
	                if($v['goodsStock']<$vv['goodsNums']){
	                   $i=1;
	                   break;
	                }
	            }
	        }
	        if($i){
	            break;
	        }
	    }
	    if($i){
	        //部分商品没货
	        $this->ajaxReturn(array('status'=>1,'msg'=>'商品库存不足'));
	    }else{
	        $this->ajaxReturn(array('status'=>0,'msg'=>'状态正常，可支付'));
	    }
	}
	
	//登录一元夺宝
	public function loginYYDB(){
	    $phone=I('phone');
	    if(!$phone){
	        //手机号码为空
	        $this->ajaxReturn(array('status'=>-2));exit;
	    }
	    $phone=$this->encrypt($phone, C('YYDB_KEY'));
	    $this->ajaxReturn(array('status'=>0,'mobile'=>$phone));
	}
	
	function postCurl($info,$url,$key)
	{
	    $data=$info;
	    $this->clearEmpty($data);
	    $data['sign']=$this->checkSign($data);
	    foreach ($data as $k=> $v){
	        $data[$k]=$this->encrypt($v, $key);
	    }
	    $ch=curl_init();
	    curl_setopt($ch, CURLOPT_URL, $url);
	    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	    curl_setopt($ch, CURLOPT_POST, 1);
	    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
	    $output = curl_exec($ch);
	    curl_close($ch);
	    return $output;
	}
	
	// 验证签名
	public function checkSign($arr){
	    $str='';
	    unset($arr['sign']);
	    sort($arr);
	    foreach ($arr as $k=>$v){
	        $str.=$k.'='.$v.'&';
	    }
	    $str=rtrim($str,'&');
	    $str.=C('YYDB_KEY');
	    return strtoupper(md5($str));
	}
	 
	//去除为空的数据
	public function clearEmpty(&$arr){
	    foreach ($arr as $k=>$v){
	        if(empty($v)){
	            unset($arr[$k]);
	        }
	    }
	}
	
	//加密算法
	public function encrypt($data, $key)
	{
	    $key    =   md5($key);
	    $x      =   0;
	    $len    =   strlen($data);
	    $l      =   strlen($key);
	    for ($i = 0; $i < $len; $i++)
	    {
	        if ($x == $l)
	        {
	            $x = 0;
	        }
	        $char .= $key{$x};
	        $x++;
	    }
	    for ($i = 0; $i < $len; $i++)
	    {
	        $str .= chr(ord($data{$i}) + (ord($char{$i})) % 256);
	    }
	    return base64_encode($str);
	}
	
	//解密算法
	public  function decrypt($data, $key)
	{
	    $key = md5($key);
	    $x = 0;
	    $data = base64_decode($data);
	    $len = strlen($data);
	    $l = strlen($key);
	    for ($i = 0; $i < $len; $i++)
	    {
	        if ($x == $l)
	        {
	            $x = 0;
	        }
	        $char .= substr($key, $x, 1);
	        $x++;
	    }
	    for ($i = 0; $i < $len; $i++)
	    {
	        if (ord(substr($data, $i, 1)) < ord(substr($char, $i, 1)))
	        {
	            $str .= chr((ord(substr($data, $i, 1)) + 256) - ord(substr($char, $i, 1)));
	        }
	        else
	        {
	            $str .= chr(ord(substr($data, $i, 1)) - ord(substr($char, $i, 1)));
	        }
	    }
	    return $str;
	}
	
	//检测店铺营业状态
	public function checkShopStatus(){
	    //店铺状态
	    $shopId=I('shopId',0,'intval');
	    $shopInfo=M('shops')->where(array('shopId'=>$shopId))->find();
	
	    if($shopInfo['shopFlag']!=1||$shopInfo['shopStatus']!=1||empty($shopInfo)){
	        $this->ajaxReturn(array('status'=>-3,'msg'=>'店铺状态异常！'));return;
	    }
	    //检查营业时间
	    $S1=$shopInfo['serviceStartTime'];
	    $E1=$shopInfo['serviceEndTime'];
	    $S2=$shopInfo['serviceStartTime2'];
	    $E2=$shopInfo['serviceEndTime2'];
	    $H=intval(date('G'));
	    $status=false;
	    if($S1>$E1){
	        if($H>=$S1){//当前时间大于开始时间
	            $status=true;
	        }else if($E1>$H) {//结束时间大于当前时间
	            $status=true;
	        }
	    }else{
	        //当前时间在开始和结束之间
	        if($S1==0&&$E1==0){
	             
	        }else{
	            if($H>=$S1&&$H<$E1){
	                $status=true;
	            }
	        }
	    }
	    if(!$status){
	        if($S2>$E2){
	            if($H>=$S2){//当前时间大于开始时间
	                $status=true;
	            }else if($E2>$H) {//结束时间大于当前时间
	                $status=true;
	            }
	        }else{
	            //当前时间在开始和结束之间
	            if($S2==0&&$E2==0){
	                 
	            }else{
	                if($H>=$S2&&$H<$E2){
	                    $status=true;
	                }
	            }
	        }
	    }
	    //休息中，或者非店铺营业时间
	    if(!$status||$shopInfo['shopAtive'] == 0){
	        if(!$status){
	            $this->ajaxReturn(array('status'=>-4,'msg'=>'非营业时间！'));return;
	        }
	        if($shopInfo['shopAtive'] == 0){
	            $this->ajaxReturn(array('status'=>-5,'msg'=>'店铺打烊啦！'));return;
	        }
	    }
	
	    $this->ajaxReturn(array('status'=>0,'msg'=>'正在营业中'));return;
	}
	
	/**  * @desc 根据两点间的经纬度计算距离
	 *  * @param float $lat 纬度值
	 *   * @param float $lng 经度值
	 *    */
	private   function getDistance($lat1, $lng1, $lat2, $lng2)
	{  $earthRadius = 6367000;
	//approximate radius of earth in meters
	/*  Convert these degrees to radians  to work with the formula  */
	$lat1 = ($lat1 * pi() ) / 180;
	$lng1 = ($lng1 * pi() ) / 180;
	$lat2 = ($lat2 * pi() ) / 180;  $lng2 = ($lng2 * pi() ) / 180;
	/*  Using the  Haversine formula    http://en.wikipedia.org/wiki/Haversine_formula    calculate the distance  */
	$calcLongitude = $lng2 - $lng1;
	$calcLatitude = $lat2 - $lat1;
	$stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);
	$stepTwo = 2 * asin(min(1, sqrt($stepOne)));
	$calculatedDistance = $earthRadius * $stepTwo;
	return round($calculatedDistance);
	}
	
}
